Andrzej
Andrzej

Reputation: 33

jQuery .on('click') duplicate ajax calls

I have a problem with duplicate ajax calls in my app. Here is my jQuery code:

$(document.body).on('click', 'a.sample', function(event) {
   event.preventDefault();

   $('#UniqueFormId').submit(function(event) {
      event.preventDefault();

      // HERE IS AJAX CALL //

      return false;
   });
});

The problem appears when I click a few times on a.sample button without submit a #UniqueFormId form. And next click button with submit form make duplicate ajax calls.

I use $(document.body) because I wont use it globaly after ajax calls. How I can avoid duplicate ajax calls?

Upvotes: 3

Views: 5471

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could disable the button after click event then enable it after success/error callback of ajax request :

$('#UniqueFormId').submit(function(event) {
      event.preventDefault();

      var _this = $(this);
      _this.attr('disabled', 'disabled'); //disable the button

      // IN AJAX CALLBACK
      _this.removeAttr('disabled'); //enable the button again

      return false;
});

$(document.body).on('click', 'a.sample', function(event) {
   event.preventDefault();

   //Load your Modal here
});

Hope this helps.

Upvotes: 1

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

You can 1 use a simple flag that doesn't rely on any DOM interaction, and then also 2 refactor the submit handler to be set outside of the click event. You just want the click event to fire the ajax submit, not set the handler.

In this case, is_sending will force the submit function to back off if it is set to true. You can see that this is set in the beforeSend callback, and cleared in the complete callback (called on both success and error, so it will always allow a retry. Mod this to your liking...)

Hope this helps and makes sense! This pattern should ensure that only one ajax request is active at any given time for this particular form.

var is_sending = false; // Default to false, then set to true when ajax request starts...

$(document.body).on('click', 'a.sample', function(event) {
   event.preventDefault();
   $('#UniqueFormId').submit();
});

$('#UniqueFormId').submit(function(event) {
    event.preventDefault();
    if (is_sending) return false;
    $.ajax({
      ...
      beforeSend: function () {
        is_sending = true;
      },
      complete: function () {
        is_sending = false;
      },
      success: function (response) {
        // Do whatever...
      }
    });
 });

Upvotes: 1

MakeLoveNotWar
MakeLoveNotWar

Reputation: 954

Just separate your submit() and click() functions

$('#UniqueFormId').submit(function(event) {
  event.preventDefault();

       // HERE IS AJAX CALL //

       return false;
   });

$(document.body).on('click', 'a.sample', function(event) {
    event.preventDefault();
   $('#UniqueFormId').submit();
 });

Upvotes: 0

Related Questions