Reputation: 2716
So, I've got this submit handler. When the request is made, I've got the form configured to point to a multi-part resource URL (it refers to an object and a child object, each with specified IDs, as part of the path). Whenever I submit the form, not only does it submit the intended request, it also makes a second request with the ID and name of the child object removed from the request URL.
TL;DR: It makes requests to /foo/1/bar/2
then /foo/1
, and I need it to stop making that second request.
I've used the standard event.preventDefault()
and thrown in return false
for good measure. Not seen here, but I've also tried $form.submit(false)
as I'd seen on another SO answer somewhere, but removed it since it looks bad and didn't work anyway.
function submitForm(e) {
e.preventDefault();
var $form = $(e.target);
$form.find('[type="submit"], [type="button"]').prop('disabled', true);
var formData = {
// data
};
$.ajax({
url: $form.prop('action'),
method: ($form.find('[name="_method"]').val() || $form.prop('method')),
data: formData,
error: function(response, status) {
console.log(response);
},
success: function(response, status) {
console.log(response);
},
complete: function() {
$form.find('[type="submit"], [type="button"]').prop('disabled', false);
}
});
return false;
}
$(document).ready(function(){
$('#myform').on('submit', submitForm);
});
I'm sure there's a problem somewhere with the AJAX call since removing it causes the form submission to stop as expected. I suppose it's also possible that the AJAX call itself is actually making two requests, but it makes no sense to me why it would do that. It also seems to happen whether the user presses the enter key or actively clicks the submit button.
Upvotes: 0
Views: 436
Reputation: 2716
I wasn't looking closely enough at the responses I was getting because I was so hung up on the fact I was seeing two outgoing HTTP requests.
The first request was coming back with a 3xx status code, so jQuery was running the second query to the URL it was being redirected to in the first response.
The service controller I was using was not handling AJAX requests properly, so upon modification of the controller to send a different response to AJAX requests, I am no longer getting the issue.
Upvotes: 1
Reputation: 23690
Chances are that you're subscribing to the submit request twice, hence the double triggering of the event. Try ensuring that you unbind first before binding:
$(document).ready(function(){
$('#myform').off('submit').on('submit', submitForm);
});
Some people say that you should use unbind/bind together as good practice. This is the same thing, but using off
instead of unbind
.
It could also be that you've included the script twice into your pages... check that too!
Upvotes: 0