Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax, prevent multiple request on click

I'm trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn't work. Just the first time works fine, then return false..

$('#do-login').click(function(e) {     e.preventDefault();      if ( $(this).data('requestRunning') ) {         return;     }      $(this).data('requestRunning', true);      $.ajax({         type: "POST",         url: "/php/auth/login.php",         data: $("#login-form").serialize(),         success: function(msg) {             //stuffs         },         complete: function() {             $(this).data('requestRunning', false);         }     });       });  

Any ideas? Thanks!

like image 559
mauriblint Avatar asked Sep 12 '13 22:09

mauriblint


People also ask

How do I stop multiple Ajax calls from repeated clicks?

click(function(e) { e. preventDefault(); if ( $(this). data('requestRunning') ) { return; } $(this). data('requestRunning', true); $.

Can we execute run multiple Ajax request simultaneously in jQuery?

To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the Ajax requests are finished. In case where multiple Deferred objects are passed to $. when() , it takes the response returned by both calls, and constructs a new promise object.

What is async in Ajax jQuery?

The jQuery Ajax async is handling Asynchronous HTTP requests in the element. It is a procedure to send a request to the server without interruption. It is an Asynchronous method to send HTTP requests without waiting response. It is a function to working on a server without associating more than on request.


2 Answers

The problem is here:

    complete: function() {         $(this).data('requestRunning', false);     } 

this no longer points to the button.

$('#do-login').click(function(e) {     var me = $(this);     e.preventDefault();      if ( me.data('requestRunning') ) {         return;     }      me.data('requestRunning', true);      $.ajax({         type: "POST",         url: "/php/auth/login.php",         data: $("#login-form").serialize(),         success: function(msg) {             //stuffs         },         complete: function() {             me.data('requestRunning', false);         }     });       });  
like image 63
Joe Frambach Avatar answered Sep 20 '22 17:09

Joe Frambach


Use on() and off(), that's what they are there for :

$('#do-login').on('click', login);  function login(e) {     e.preventDefault();     var that = $(this);     that.off('click'); // remove handler     $.ajax({         type: "POST",         url: "/php/auth/login.php",         data: $("#login-form").serialize()     }).done(function(msg) {         // do stuff     }).always(function() {         that.on('click', login); // add handler back after ajax     }); });  
like image 20
adeneo Avatar answered Sep 20 '22 17:09

adeneo