Andrzej Andrzej - 4 months ago 30
jQuery Question

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?

Answer

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.

Comments