jQuery AJAX is the most common way to deal with AJAX request these days. You can send as many ajax request as you like but there are many cases in which sending too many or frequent ajax request is not suitable and best avoided. For example let’s say you have developed a certain search functionality which fetches result data using AJAX. The search query string is the value of the input field binded with the ajax function and is triggered on the keyup event on the input field. In this case if the user has to enter a query string of let’s say 8 characters, so this will mean that there’ll be at least 8 keyup events triggered, which further means that there’ll be at least 8 ajax calls. This will definitely lead to slowing of the whole app and is unreasonable as well. The solution here is to only focus on the query string after the user has finished typing i.e. the last keyup event. So, for this you have to cancel or abort all the previous ajax requests.

Let’s say that the input field is as follows:

<input type="text" name="search" id="search" value="" />

Now, we have to write the code for the ajax function which will be triggered on the keyup event and will also abort the previous ajax calls if any. So, our code for such function will be as:


// A $( document ).ready() block.
$( document ).ready(function() {
    var ajaxReq = 'ToCancelPrevReq'; // you can have its value anything you like
    $( "#search" ).keyup(function() {

        var queryString = $( "#search" ).val();

        if(queryString == '') return; //You can always alter this condition to a better one that suits you.

		ajaxReq = $.ajax({
					url: YourPostURL, //Don't forget to replace with your own post URL
					type: 'POST',
					data: {'query': queryString},
					dataType: 'JSON',
					beforeSend : function() {
							if(ajaxReq != 'ToCancelPrevReq' && ajaxReq.readyState < 4) {
					success: function(json) {
					error: function(xhr, ajaxOptions, thrownError) {
							if(thrownError == 'abort' || thrownError == 'undefined') return;
							alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
		          }); //end ajaxReq
	}); //end keyup

});//end document.ready


In the above code what’s happening is that we have assigned our $.ajax request to a variable ‘ajaxReq‘. This variable will hold the current ajax request object and if another ajax request is called before the previous one is completed it aborts the previous one. It does this by checking the condition set in the beforeSend setting function which fires before a new ajax request is initiated. The ajaxReq != ‘ToCancelPrevReq’ checks if the ajaxReq variable holds a previous ajax request object and the ajaxReq.readyState < 4 condition checks if that is complete or not. The readyState property can have 5 values depending on the status of the ajax XMLHttpRequest, these are:


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready


You can learn more about XMLHttpRequest at:


Now, most of the tutorials regarding this topic end here, but aborting the previous request creates another problem if you are catching errors in case of failed ajax request. You’ll notice that in the error setting function we have an alert capturing any error that is returned in case of a failed request, its status and its responseText. Since when we abort a request it’s considered as a failed request that will also be captured. But we don’t want to display an alert every time a user types fast and cancel previous ajax request in the process, so we add our condition to ignore the ‘abort’ error and just to be safe any ‘undefined’ error as well. The condition:
if(thrownError == ‘abort’ || thrownError == ‘undefined’)

checks this and return if true, without processing the further alert.


This is it. This should be a standard and should also be considered a good practice as well.


Feel free to suggest any other good methods that you may have. Happy Coding 🙂


  1. Interesting article thank you for sharing


  2. gracias por compartir, me ayudo bastante.


  3. Brajinder Singh

    Sorry man! Your website doesn’t seem to work for me in any browser. Let me know if you need my help on anything else.


    • Hey Brajinder, Sorry to be the bearer of bad news, but at least two of three of the comments you’ve replied to so far are spam. You really should delete spam from your blog least you encourage more of the dreadful practice.


      • Brajinder Singh

        Thanks for the concern. May be they are may be they aren’t. The websites they have linked isn’t working. So, I’m going to give them the benefit of doubt here and leave it as it is. I have a few plugins which monitor spam. Still, thanks for your concern. Really appreciated.


  4. Great, great, great, thanks for publishing. 🙂


  5. I have 2 tabs, each tab have same function i.e. generateReport() which call same ajax call.
    on the tab delete, i put a abort() function.
    if i hit the both function, which create 2 ajax call. and delete 1no tab immediately then my abort function run and cancel the 2nd no ajax call.
    expectation is 1no ajax call will be canceled.
    Any idea about this issue?


    • Brajinder Singh

      Your logic seem flawed or I might be way off in thinking what you have done. Without seeing the actual implementation it’s hard for me to figure out. The best I can say at the moment is use ID based approach, and use this.id to make sure only the selector is acted upon. It’s been a lot of time since you posted it so I assume it’s resolved by now. Anyhow, thanks for going through 🙂


  6. Cool, thanks


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.