Understanding AJAX

Understanding AJAX

Understanding AJAX

AJAX; Asynchronous JavaScript And XML; is the most commonly used term in Web Development. For those who are aware of AJAX, its not a problem; but for those who are beginners of web development face the problem in understanding and working with the AJAX.

Asynchronous JavaScript and XML (AJAX) is a set of things working together to achieve a rich internet browsing experience. AJAX does so by enabling the developer to load the page sections asynchronously from the server without making user to wait for the page to be loaded completely.

Asynchronous means in background without making the user to wait for the request to get completed.

So now how this request in known and how it works we will see.

First step is to create request and then send it to the server. So an XMLHttpRequest or ActiveXObject has to be created for this.

var xhr = false;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
	xhr =new XMLHttpRequest();
} else {// code for IE6, IE5
	xhr =new ActiveXObject("Microsoft.XMLHTTP");
}

Above was the creation. Now it has to be sent. It can be sent as a GET or POST request. Basically for sending the request two methods are used open and send For GET request:

xhr.open("GET","callback.php?data=datavalue",true);
xhr.send();

For POST request the request header must be set as “application/x-www-form-urlencoded“. So:

xhr.open("POST","callback.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("data=datavalue");

Now as the request is sent; we will wait for the response and check whether the request is completed and with proper response. So for this there is a event handler for this “onreaystatechange” which will be triggered everytime when there is a change in the ready state “readyState“. The following can be the possible values of the readyState

0 UNINITIALIZED The object has been created, but not initialized (the open method has not been called).
1 LOADING The object has been created, but the send method has not been called.
2 LOADED The send method has been called, but the status and headers are not yet available.
3 INTERACTIVE Some data has been received. Calling the responseBody and responseText properties at this state to obtain partial results will return an error, because status and response headers are not fully available.
4 COMPLETED All the data has been received, and the complete data is available in the responseBody and responseText properties.

Now along with that we can handle the responses received from the sever. To handle the response status property of the XMLHttpRequest (xhr) object is used. Some of the HTTP status codes are as follows:

A full info on HTTP status codes can be found on following URLs:

Code Code Description
200 The request is OK (this is the standard response for successful HTTP requests)
400 The request cannot be fulfilled due to bad syntax
404 The requested page could not be found but may be available again in the future
500 A generic error message, given when no more specific message is suitable
502 The server was acting as a gateway or proxy and received an invalid response from the upstream server

http://www.w3schools.com/tags/ref_httpmessages.asp
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http://httpstatus.es/

And depending upon the combinations of the readyState and status we can handle the AJAX response properly. Moreover you can use the statusText property to check what status text has been returned from server.

So the readyState as 4 and the status as 200 ( means statusText as “OK” ) states that the request in complete and the proper response is available. So the code to handle this is as follows:

xhr.onreadystatechange = function()
{
	if ( 4 == xhr.readyState && 200 == xhr.status )
	{
		//code to handle response and DOM manipulation
	}
}

Now the response is contained by the responseText or responseXML property of XMLHttpRequest object. So if response is returned as XML; you can use responseXML property to use it and if response is returned as HTML string or JSON string then you can use the responseText property. For JSON you need to eval the text returned.

Lets consider XML response. Following is the XML received from the server (server will also has to return Content-Type as “text/xml“)

<?xml version="1.0" encoding="ISO-8859-1"?>
<USERS>
	<USER>
		<NAME>Pankaj Patel</NAME>
		<URL>http://pankaj.pro</URL>
	</USER>
	<USER>
		<NAME>Time to Hack</NAME>
		<URL>http://time2hack.com</URL>
	</USER>
</USERS>

And to handle above response following is the code

xhr.onreadystatechange = function()
{
	if ( 4 == xhr.readyState && 200 == xhr.status )
	{
		if( null == xhr.responseXML ){

			xml = xhr.responseXML;
			txt = "<table>";
			names = xml.getElementsByTagName("NAME");
			urls = xml.getElementsByTagName("URL");
			for ( i=0; i < names.length; i++ ) {
				txt += "<tr>";
				txt += "<td>" + names[i].childNodes[0].nodeValue + "</td>";
				txt += "<td>" + urls[i].childNodes[0].nodeValue + "</td>";
				txt += "</tr>";
			}
			txt += "</table>";
			document.getElementById('targetDiv').innerHTML = txt;
		}
	}
}

And if the response is received as plain text then we can us the responseText property. For example in place of sending the XML; server send the already crafted table html as plain text then it can be handled as below:

xhr.onreadystatechange = function()
{
	if ( 4 == xhr.readyState && 200 == xhr.status )
	{
		if( null == xhr.responseText ){
			document.getElementById('targetDiv').innerHTML = xhr.responseText;
		}
	}
}

So now on combining all the above codes and cases the final code will look like this

var xhr = false;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
	xhr =new XMLHttpRequest();
} else {// code for IE6, IE5
	xhr =new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.open("POST","callback.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("data=datavalue");

xhr.onreadystatechange = function()
{
	if ( 4 == xhr.readyState && 200 == xhr.status )
	{
		if( null == xhr.responseXML ){

			xml = xhr.responseXML;
			txt = "<table>";
			names = xml.getElementsByTagName("NAME");
			urls = xml.getElementsByTagName("URL");
			for ( i=0; i < names.length; i++ ) {
				txt += "<tr>";
				txt += "<td>" + names[i].childNodes[0].nodeValue + "</td>";
				txt += "<td>" + urls[i].childNodes[0].nodeValue + "</td>";
				txt += "</tr>";
			}
			txt += "</table>";
			document.getElementById('targetDiv').innerHTML = txt;
		} else if( null == xhr.responseText ){
			document.getElementById('targetDiv').innerHTML = xhr.responseText;
		} else {
			document.getElementById('targetDiv').innerHTML = "The AJAX request returned a NULL response";
		}

	}
}

I have tried to cover the vey basics for AJAX and I hope I did it but if you need very detailed study on the XMLHttpRequest then go through https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest. More suggestions and corrections(if any) are welcome.


Got Something To Say:

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

*