views:

45

answers:

3

How do prevent like if a user clicks alot of times on a link that runs a ajax call, that it only run again after the it has been succeed

+2  A: 

I think this might be my first answer on stackoverflow. Anyway, if you mean what I think you mean, then as soon as the button is clicked you'd disable the button in your ajax function (before you get to the actual making of an http request). Then once your ajax call is complete your onreadystate function would re-enable it.

to disable a button, if it has an id.

document.getElementById("theidofthebutton").enabled = false;

to re enable it...

document.getElementById("theidofthebutton").enabled = true;

Edit: I see you're refering to a link not a button. I could be wrong but I think you can still disable in the same way.

MrVimes
MrVimes - I was thinking you may be on to something about disabling the link, but I did a quick test. Doesn't seem to work. http://jsfiddle.net/KkYCm/
patrick dw
+2  A: 

One simple solution is to add a class to the link when the user clicks, and remove the class when the response is received.

Each click of the link checks to see if the pending class exists, and only sends the AJAX request if not.

Then the complete: callback removes the pending class.

$('a.myLink').click(function() {
    var $th = $(this);
    if( !$th.hasClass('pending') ) {
        $th.addClass('pending');
        $.ajax({
          url:'something',
          complete: function() {
              $th.removeClass('pending');
          }
        });
     }
});
patrick dw
Since you're using jQuery, you could also use jQuery.data() to attach this 'pending' data valueSee: http://api.jquery.com/jQuery.data/
Dancrumb
@Dancrumb - That's true. Nice thing about adding a class is that you can use it to provide the user some visual feedback to show that the link isn't clickable. I'd bet that it is a faster operation than accessing `.data()` as well. Not sure though.
patrick dw
A: 

Try using the jquery plugin BlockUI to block the user from clicking the link again. This can be done at the Element or Page level.

// unblock when ajax activity stops 
$(document).ajaxStop($.unblockUI); 

function test() { 
    $.ajax({ url: 'wait.php', cache: false }); 
} 

$(document).ready(function() { 
    $('#pageDemo2').click(function() { 
        $('div.test').block({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' }); 
        test(); 
    });  
});
Randall Kwiatkowski