Ajax, prevent multiple request on click
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); } }); });
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 });});