Tutorial Categories:

HTML/CSS JavaScript/AJAX Server-Side Marketing General Comp-Sci

An Introduction to AJAX

By Justin Poirier

Asynchronous JavaScript And XML (AJAX) refers to the use of a client-side scripting language (often JavaScript) to request data from the server, then using the data to update only part of a page.

The request can be made from the code in any <script> element. Often it's from some function that is responding to a change in a field as registered by the onchange, onsubmit, etc. attributes. When the response arrives, it is handled by a function written for this purpose and registered for automatic callback.

The step-by-step process from the event signifying that data will be downloaded to the handling of the data when it arrives is listed below. This is the process from the point of view of the client-side script; it assumes that the data that it needs, or scripts that will generate this data, are already present on the server. Note that this is not an algorithm, as only steps 1 through 4 will occur in the same execution of script code in the browser. Step 5, which deals with the HTTP response carrying the requested data, will occur at an unkown time, when the arrival of the response triggers the execution of the handler function.

When passages of code are used in the following, the language is JavaScript.

  1. Create the request object.

    This is accomplished using the following function.

    function getRequestObject () {
    	// First we get an HTTP object:
    	var XMLHttp=null;
    	try {
    		XMLHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	}
    	catch(e) {
    		try {
    			XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
    		} catch (e2) {}
    	}
    
    	if (XMLHttp==null) {
    		XMLHttp=new XMLHttpRequest();
    		/* UN-COMMENT THE FOLLOWING 'IF' BLOCK IF THE RETURNED DATA WILL BE XML.
    		   NOTE: SOME SOURCES RECOMMEND LEAVING THIS LINE IN AT ALL TIMES,
    		   OR ELSE CERTAIN VERSIONS OF MOZILLA WILL RETURN AN ERROR. HOWEVER,
    		   OTHERS POINT OUT THAT LEAVING IT IN WHEN THE RETURNED DATA
    		   IS NOT XML WILL RETURN AN ERROR IN CERTAIN VERSIONS OF FIREFOX. SO
    		   WE WILL ONLY PUT IT IN WHEN THE RETURNED DATA IS DEFINITELY XML.
    		*/
    		/*
    		if (XMLHttp.overrideMimeType) {
    			XMLHttp.overrideMimeType('text/xml');
    		}
    		*/
    	}
    	return XMLHttp;
    }
    
  2. Register the function that will handle the HTTP response carrying the data when it arrives.

    Note that while, in the assignment of a JavaScript variable representing a function, the function name can simply be stated, we will instead set the handler function equal to an anonymous function. The JavaScript format for doing this is function () {function contents}. This anonymous function will then call the function we will write (called "handler()" in the example below) to actually handle the response. By doing it this way, we can make the handler receive the request object as a parameter (it will need it, as step 5 will show). We cannot simply make the request object global, or it would be overwritten by any repeated executions of the code. The code for the registering of the function follows.

    Name of request object.onreadystatechange = function () {
    	handler (Name of request object);
    }
    
  3. Open the connection through which the request will be sent.

    Name of request object.open(Type of message, as a string1, URL of data to receive, true or false2);
    1 E.g. "GET" or "POST"
    2 Whether to have execution continue while request sent to server

    If the message type used is "POST", we must then set the data format for the message body, which is represented in all HTTP requests and responses by the header field "Content-Type". In the following line we set the Content-Type to "application/x-www-form-urlencoded".

    Name of request object.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

    While the Content-Type value "application/x-www-form-urlencoded" seems to imply that the data will be appended onto the end of the URL as with a "GET" request, the Content-Type refers to only the message body, and the value "application/x-www-form-urlencoded" simply means the data in the body is in the format name=value&name=value&..., as is used when data is appended onto an URL with a "GET" request. Note that the reason we didn't have to set the Content-Type when using "GET" is that the message body is empty when using "GET".

  4. Send the request.

    This is accomplished with the line:


    Name of request object.send(data if POST or null if GET);
  5. Handle the response when it arrives.

    The outline of the handler() function follows. This function gets called repeatedly from the time the request is sent, and it must check if the response is fully received and do nothing until it is. When the readyState parameter of the request object has a value of 4 it means the response is fully received, hence the "if" block in the code checking if this is the case.

    function handler(requestParam) {
    	try {
    		if (requestParam.readyState == 4) {
    			if (requestParam.status == 200) {
    				Code to handle response
    			} else {
    				alert ("There was a problem retrieving data from the web server.");
    			}
    		}
    	} catch (e) {
    		alert ("There was a problem retrieving data from the web server.");
    	}
    }
    

    If you've chosen to structure the data served to the client in an application-specific format, the responseText parameter of the request object can be used to obtain the data as a string. It is often beneficial to use a standardized data format, particularly XML or JSON, for the data. If JSON is used, the responseText parameter should again be used, to obtain the JSON-formatted string of data. If XML is used, the responseXML parameter of the request object can be used. It points to a DOM object automatically created for the data defined by the XML. For more information on how to convert a JSON-formatted string returned by responseText to a tree of objects, and how to deal with a DOM object created from XML, please see Classroom306's lesson An Introduction to DOM Objects and JSON.

If the request calls a script that generates XML, that script must set the following header fields in the response before sending it back:

Content-Type: text/xml
Cache-control: no-cache