jQuery AJAX form submits twice

James Privett picture James Privett · Nov 25, 2013 · Viewed 59.6k times · Source

I've got a form that I'm capturing via jQuery and sending via AJAX. My problem is that the form submits more than once every time I refresh the page.

I've tried to unbind the submit button but then the form is posted normally after the first submit. Any help would be appreciated

$('#exportForm').submit(function() {
  $.ajax({
    type: "POST",
    url: $(this).attr('action'),
    data: $(this).serialize(),
    success: function(response) {
      $('#exportForm').unbind('submit');
      console.log(response);
    }
  });
  return false;
});

Answer

Chris Sercombe picture Chris Sercombe · Oct 8, 2014

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;
});