JQuery :: How to know when ajax request has completed!

In our previous article which was JQuery :: How to do action on an element on key press? we discussed how we can take an action on an element when a key is pressed. Today we will like to discuss on an aspect which is not discussed more openly and no good information is found online as far as I know. The topic of discussion today is how can we know when an ajax request made through JQuery is complete.

Many times in development we were faced with problems like overlapping of ajax requests when sent to server via jquery. The problem was there was no clear documentation as to how we can know when ajax request has finished. The importance to know the ajax request life time is known when you have to constantly check for new stuff by automatically sending a request to server side script.

When you do not put a check in your code to know when ajax request has finished there is overlapping of requests which gets sent to server again and again before the 1st one has finished working.

In order to get status of the request currently being processed we use the JQuery function called “ajaxComplete” on document. The JQuery function ajaxComplete will execute on end of each request made to server side script via ajax.

The function is triggered each time an ajax request on your web page is completed i.e. if you have 10 ajax scripts running on your web page the function will get triggered 10 times each time when the request is complete.

In order to know when the ajax script has finished working we use the function and put a check on each ajax request sent to server.

To start make a new java script js file named “completeCheck.js” and include it in your HTML file. Once included open the java script file and add in the following code to the same:

$(document).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions)
{

}

The above code will catch the ajaxComplete event when it is triggered each time an ajax request has finished working. Now suppose you want to catch the event when a particular ajax script has finished working like e.g. you want to catch and do your work once “ajax/getContent.php” has finished loading and request is complete. To do the same you can add in the following code to your java script file:

$(document).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions)
{
if(ajaxOptions.url == “ajax/getContent.php”)
{

// do your thing….
}

}

In the above code we added a check to know when “ajax/getContent.php” has finished loading and has finished the request. You can now add in code you want to execute once that request has finished or you can recall the function to get more content after the request is complete.

We will keep updating our Jquery Tips section every 4 days, please subscribe to our feed and also share our articles on Facebook and Google Plus so other’s can benefit from our insight. Please feel free to send us your comments below, on how we can improve.