Forcing Javascript to Wait For AJAX

Forcing Javascript to Wait For AJAX

A common problem I ran into as I learned AJAX was that the javascript wouldn’t wait for the AJAX to return the content I asked for. That is because of the “A” in AJAX. AJAX is asynchronous. This means that it will send the request out and will get a response back in an indeterminate amount of time. The frustrating part is that the javascript will not wait for the response from AJAX. This in turn produced very inconsistent results depending on what ran faster. To resolve this one must find out if the AJAX is done executing before continuing to run the rest of the AJAX.

There are three ways to fixing this. The correct way of fixing this is to use:

xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
// Do things

This identifies if the AJAX has completed, and that it is ready to use the content you asked it to pull for you. Two other options you can use if you must are to have the javascript delayed by a timing event or to actually syncronize the page and the server.

AJAX(); //A function that makes the AJAX call
var t=setTimeout("javascript statement",milliseconds); //The rest of the code to be executed with the AJAX content

The above code will execute the code in the first parameter after the time has elapsed in the second parameter. This works well in many cases, but you leave yourself open to runtiime errors if the AJAX call takes longer to compelete than the timeout. This can cause issues of scalability as the database grows.

Finally, the last and least desirable way of doing this is to actually sync the client and the database. The biggest problem with this is that it will freeze up the browser as it waits to get the information it needs. Its very easy to execute. All you have to do is change the third parameter in the open method to false."GET",url,false);

[warning]Just beware of errors as the timeout period until the user gets control again can take up to 2 minutes.[/warning]


Leave a Reply

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