James Privett
James Privett

Reputation: 1109

jQuery AJAX form submits twice

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

Upvotes: 54

Views: 69602

Answers (10)

Chris Sercombe
Chris Sercombe

Reputation: 1309

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

Upvotes: 130

Eddie
Eddie

Reputation: 1536

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>

Upvotes: 0

gutkol
gutkol

Reputation: 1

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

Upvotes: 0

Vladimir Leonov
Vladimir Leonov

Reputation: 11

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

Upvotes: 1

Gammer
Gammer

Reputation: 5628

You can simply use e.stopImmediatePropagation(); :

For example :

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

Upvotes: 7

Snziv Gupta
Snziv Gupta

Reputation: 1066

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

Upvotes: 0

Adam
Adam

Reputation: 2398

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.

Upvotes: 2

Kazario
Kazario

Reputation: 1

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.

Upvotes: -3

ddanurwenda
ddanurwenda

Reputation: 153

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.

Upvotes: 11

DevlshOne
DevlshOne

Reputation: 8457

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

Upvotes: 36

Related Questions