简体   繁体   中英

Why does an ajax form inside of an if statement submit twice if it is submitted after first failing the condition?

Consider the code below. If myField1 does NOT equal myField2 , then the alert appears. When I click okay on the alert pop up my form is still there, with all of the fields still populated with the data I had previously entered. However, when I modify the fields so that myField1 DOES equal myField2 , and then submit the form it is actually submitted TWICE! Why is this?

$(document).ready(function(){
$("#myForm").submit(function() {
    var myField1 = $('#myID1).val();
    var myField2 = $('#myID2).val();
    if(myField1 == myField2)
    {
        $.ajax({
            type: "POST",
            url: 'myFile.php',
            dataType: 'html',
            data: {myData:myField1,
                   myData2:myField2},
            success: function(data){
                alert(data);
            }
        });
        return false;
    }
    else
    {
        alert('These two fields are not equal!)
    }
});
});

Okay, so I found this on another question and it solves the problem:

$('#myForm').unbind('submit').bind('submit',function() {
    // do stuff here...
});

By unbinding the event, then re-binding it, the form no longer submits twice.

Your submit event is going to fire the submit action of the form unless you prevent it from doing so. Running an AJAX call in does not prevent this from happening. You need to stop this yourself.

You need:

$("#myForm").submit(function(event) {
    event.preventDefault()
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM