jQuery - Prevent Multiple AJAX Requests

09 March 2012Junaid Qadir2 min read243 Words
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:

[gist id='820'/]

Suppose, if we call the function using a link,


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:

[gist id='823'/]

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.

Share this post
How do you feel about this article?