I have a simple AJAX form that works as it should when I submit it. However, if I then enter new data into the same form (without refreshing the page), then it submits the form twice. If I do this a third time, then it submits the form three time, and so on. Why is it doing this? Here is my code:
$(document).ready(function(){
$("#myForm").submit(function() {
var myField = $('#myID).val();
$.ajax({
type: "POST",
url: 'myFile.php',
dataType: 'html',
data: {myData:myField},
success: function(data){
alert(data);
}
});
return false;
});
});
Even I got stuck with the same problem while developing a AJAX login form. After an googling for couple of hours I found a solution. I hope this should help you out.
Basically you have to unbind the current instance of form's submit action after your ajax request gets completed. So add this line before return false;
$("#myform").unbind('submit');
Therefore your entire code should look like
$(document).ready(function(){
$("#myForm").submit(function() {
var myField = $('#myID).val();
$.ajax({
type: "POST",
url: 'myFile.php',
dataType: 'html',
data: {myData:myField},
success: function(data){
alert(data);
}
});
/* Add this line */
$("#myform").unbind('submit');
return false;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With