jQuery AJAX form submits twice
It's most likely that you're using a button
or submit
to trigger the ajax event. Try this:
$('#exportForm').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});
In case you are using some kind of validation (e.g jQuery Validation), the form is submitted twice because aside from $('#exportForm').submit
you write yourself, the validation plugin will also submit the form after it successfully validates all field.
NB : If you are using jQuery Validation, avoid using .submit()
. Instead, use submitHandler
.
As well as calling preventDefault
, also call stopImmediatePropagation
on the event.
$('#exportForm').submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});