简体   繁体   中英

Why does jquery submit my ajax form twice?

When my form is submitted php will return false if it doesn't like the values contained in field1 and field2 . If it does like those fields, then it will return true . If a user submits the form and php returns false , then an alert appears. After closing the alert window, if the user immediately enters new (good) data into those fields and submits the form again, then the form is somehow submitted twice. Why? How can I fix this?

$("form#myForm").on('submit',function() 
{
    $.ajax(
    {
        type: "POST",
        url: 'myfile.php',
        dataType: 'html',
        data: 
        {
            field1:$("input[name=field1]").val(),
            field2:$("input[name=field2]").val()
        },
        success: function(data)
        {
            if(data == false) 
            {
                alert('hello world');
            } 
            else 
            {
                // stuff
            }
        }
    });
    return false;
});

The same question was asked in 2014 ( jquery ajax form submits twice ).

e.preventDefault() on its own works for buttons and anchor links but didn't work for me when submitting a form (identical to Nancy 's code above).

I had to add e.stopImmediatePropagation(); just before my ajax post. This stopped the ajax call from being submitted twice.

add this code after below, before return false

$('#myForm').unbind('submit');
 return false;

Because you're doing the ajax post you'll need to disable the default submit button behavior. See http://api.jquery.com/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