jQuery – Prevent Multiple AJAX Requests


Many times we do not want to take any other requests of the same type while one is still in progress.
A normal post request looks something like:

function doSignup(){
    $.post('http://my-awsomesite/ajax.php',  $('#signupForm').serialize(),
    function(resp){
        if(resp.status == 'OK'){
            alert("Success message");
        }else{
            alert("duh! Signup failed");
        }
    }, 'JSON');
}

Suppose, if we call the function using a link,

<a href="javascript:doSignup()">Signup</a>

Someone does repeated clicks and an enormous amount of requests will be off their way to choke the server to death!
So, to process one request at a time, we’ll modify the above function to something like this:

/**
 *Let's define a variable that acts similar to the 'On Air' light. When
 *its active (true in this case), we will just return from the doSignup function
 * silently or inform the user via a jquery-ui dialog or something like that.
 */
var isProcessing = false;

function doSignup(){
    if(isProcessing){
        /*
         *This won't go past this condition while
         *isProcessing is true.
         *You could even display a message.
         **/
        return;
    }

    /**
     *set isProcessing to true right before the $.post (or anyother method
     *of the sort like $.ajax, $.get) is called
     */
    isProcessing = true;
    $.post('http://awsomesite/ajax.php',  $('#signupForm').serialize(),
        function(resp){
            isProcessing = false;
            if(resp.status == 'OK'){
                alert("Success message");
            }else{
                alert("duh! Signup failed");

            }
        }, 'JSON');
}

The code is pretty straight-forward, you define a variable that is visible to your function.
Then inside your function you write a conditional statement to check whether the variable is true, initially it is false.
If it’s false then the code continues and just before the AJAX action (get, post, etc) is performed, you’ll change the variable to true. And as soon as the AJAX action completes its trip to the server, you turn that variable to false again.
While the AJAX action is processing if the user tries to click the signup link, either you prompt him/her to wait or simply ignore his actions.

As I mentioned earlier of repeated user clicks, another concern arises, we have to tackle after how much delay a request should go in order to prevent unnecessary requests to the server. I’ll try to cover that in a future post.

Thanks for reading, have a great weekend.