jQuery AJAX form submits twice

JqueryAjaxSubmit

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

It's most likely that you're using a button or submit to trigger the ajax event. Try this:

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

        return false;
    });

Solution 3 - Jquery

In case you are using some kind of validation (e.g jQuery Validation), the form is submitted twice because aside from $('#exportForm').submit you write yourself, the validation plugin will also submit the form after it successfully validates all field.

NB : If you are using jQuery Validation, avoid using .submit(). Instead, use submitHandler.

Solution 4 - Jquery

You can simply use e.stopImmediatePropagation(); :

For example :

$('#exportForm').submit(function(e){
    e.stopImmediatePropagation();

Solution 5 - Jquery

As Chris Sercombe pointed out, e.stopImmediatePropagation() does work and it definitely fixes the problem, but you shouldn't have to use it. The problem still exists in your code somewhere. Let me mention an example of how two post requests could be sent:

If you are using AngularJS, and lets say you make a controller called "HandleAjaxController" you could assign this ng-controller to a div, and then accidentally assign this same ng-controller to an inner div. This would cause the post request to be sent twice. So:

    <div ng-controller='HandleAjaxController'>
        <div ng-controller='HandleAjaxController'>
            <button id="home" type="button" class="btn btn-success">Send data</button>

This caused a lot of stress for me one time because in my ng-route I had set the controller in here:

    $routeProvider
    .when("/", {
        templateUrl : "src/js/partials/home.html",
        controller : "HandleAjaxController"
    })

and then I set it again in my home.html: <div ng-controller='HandleAjaxController'>

Anyways, that is one example of how two posts could be sent.

Solution 6 - Jquery

You should check your another js code, maybe somewhere it triggers twice "submit" event. This happened in my case, i forget "return false" in onclick handler for one button

Solution 7 - Jquery

i have added jquery.unobtrusive-ajax.min.js ref twice as answered here https://stackoverflow.com/a/15041642/4412545

Solution 8 - Jquery

For someone who have almost same problem I can say that you should control your jQuery events away from function(){}, so the best to had only one request from ajax POST is to have events like this:

$(document).ready(function {
 $("#exportForm").click(function{
   $.ajax({
      type: "POST",
      url: "#", //your url
      data: data, //your variable
      success: function(){
        //do something here
      }
   });
 });
});

not in function which evokes second function like this:

$(document).ready(function {
 exportingForm();
 
 function exportingForm(){
   $("#exportForm").click(function{
     $.ajax({
        type: "POST",
        url: "#", //your url
        data: data, //your variable
        success: function(){
          //do something here
        }
     });
   });
 }
});

Solution 9 - Jquery

Just want to point out, if you have more than one element with the same class, this can happen as well.

<button class="downvote">
  <img src="/img/thumbs-down.png" class="downvote">
</button>

Solution 10 - Jquery

The problem can be resolved by using a div in place of a button on your php form. A button is not needed due to the use of ajax.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames PrivettView Question on Stackoverflow
Solution 1 - JqueryChris SercombeView Answer on Stackoverflow
Solution 2 - JqueryDevlshOneView Answer on Stackoverflow
Solution 3 - JqueryddanurwendaView Answer on Stackoverflow
Solution 4 - JqueryGammerView Answer on Stackoverflow
Solution 5 - JqueryAdamView Answer on Stackoverflow
Solution 6 - JqueryVladimir LeonovView Answer on Stackoverflow
Solution 7 - JquerySnziv GuptaView Answer on Stackoverflow
Solution 8 - JquerygutkolView Answer on Stackoverflow
Solution 9 - JqueryEddieView Answer on Stackoverflow
Solution 10 - JqueryKazarioView Answer on Stackoverflow