Asynchronous behavior of AJAX

14 / Sep / 2010 by Bhagwat Kumar 1 comments

Ajax (shorthand for Asynchronous JavaScript and XML) is used to retrieve data from the server asynchronously without interfering with the display and behavior of the existing page. Forgetting this asynchronous behavior will produce incorrect result if it depends on the response from Ajax call.

Lets take an example(I am using JQuery to illustrate the example). Here is a JavaScript function to perform server side check of the form. Depending on the response of Ajax call the function either submits the form or does nothing.

function submitForm(){
	var isFormValid=false;
	var dataToBeSent=$('form').serialize();
	$.get(url, dataToBeSent, function(result){
		isFormValid=result;
	})
	if(isFormValid){
		$('form').submit();
	}
}

The statement $('form').submit() will never be called irrespective of the result (AJAX call response). After executing $.get statement it will execute the next statement  if(isFormValid) without waiting for the statement isFormValid=result inside the callback function to be executed.

There exist a dirty solution for the problem : using JavaScript sleep API. But how long you are going to halt the execution of JavaScript code. You are back to the same problem of getting the incorrect behavior.

One good solution is to make the $.get call synchronous by making changes to the global AJAX configuration like :

$.ajaxSettings.async=false;

or using calls like :

$.ajax({type: "GET", url: url, data: dataToBeSent, success: function(){
		isFormValid=result;
	}
});

Now the if(isFormValid) statement will be executed only after the $.ajax statement has completed its execution. However this approach has its own drawback. Obvious one is the execution of JavaScript halts until it receives the response.

However the better solution  is to execute $('form').submit() inside the callback function like :

$('submitButton').click(function(){
	var isFormValid=false;
	var dataToBeSent=$('form').serialize();
	$.get(url, dataToBeSent, function(result){
		isFormValid=result;
	if(isFormValid){
		$('form').submit();
	}
	})
return false;  // Needless if the button is not a submit button
})

return false statement at the end of the function prevents the form from being submitted. Now the form submission code will be executed only after the response to $.get statement is true.

There exist JQuery plugins (e.g. JQuery validation plugin) for doing form validation in a better way where you get support for server side validation also. But the case discussed above was to make you understand the asynchronous behavior of AJAX calls.

Hope this helps you while using Ajax.  🙂

Cheers,
~~Bhagwat Kumar~~
bhagwat(at)intelligrape(dot)com

http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Asynchronous behavior of AJAX”)

Leave a Reply

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