1

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;
});
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Nancy Collier
  • 1,469
  • 4
  • 17
  • 21
  • It seems to work on [jsbin](http://jsbin.com/ujinon/3/edit), it only makes one request per submit. To make it run on jsbin, I changed `POST` to `GET`, set the url to `#`, and replaced the `data == false` with `true`. HTH – Dan Ross Feb 09 '13 at 03:04

3 Answers3

4

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.

Community
  • 1
  • 1
Robini
  • 377
  • 1
  • 3
  • 14
2

add this code after below, before return false

$('#myForm').unbind('submit');
 return false;
Rashad
  • 1,344
  • 2
  • 17
  • 33
1

Because you're doing the ajax post you'll need to disable the default submit button behavior. See http://api.jquery.com/event.preventDefault/

Jasen
  • 14,030
  • 3
  • 51
  • 68