Cricinfo Live Scores

Tuesday, February 19, 2008

Introduction to AJAX

Description: Everybody till now must have atleast heard about AJAX (Asynchronous JavaScript And XML). This example will give you an idea about how you can implement simple AJAX interaction in your web application.

Purpose of using AJAX

The main purpose of using AJAX is to asynchronously get the information from the server and update only that area of the web page where this information fetched needs to be displayed, avoiding refresh of the entire page. The other advantage of this is, the web page can hold minimal required data and retrieve rest as needed based of events.

How is all this possible.

Its possible by writing a JavaScript code in your web application, which uses XMLHttpRequest object to communicate with the server and get the data asynchronously.

The first step is to create and configure the XMLHttpRequest object.

  • Currently there are two implementations of this object, ActiveXObject is Internet ExplorerXMLHttpRequest works with other browsers. So a check is made before creating the object, like this,

    var httpRequest;
    specific, and
    if (window.ActiveXObject) // for IE
    {
    httpRequest
    = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) // for other browsers
    {
    httpRequest
    = new XMLHttpRequest();
    }
  • Now configure the object by setting the HTTP method, GET or POST, the URL of the server side element, like a servlet or cgi script, which this object will communicate with, and the third parameter is a boolean value which decides whether the interaction should be synchronous or asynchronous, where true means asynchronous.

    httpRequest.open("
    GET", url, true);
  • Then set the name of the JavaScript function, which will handle the callback from the server side element.

    httpRequest.onreadystatechange
    = function() {processRequest(); } ;
  • Now make the call,

    httpRequest.send(
    null);

Second step is to handle the response from the server which is always in XML form.

The server element can return the actual data in XML form or the formatted HTML code. This processing is done in the JavaScript function, which is specified as the callback function. The first thing to do in this method is to check the XMLHttpRequest object's readyState, value 4 indicates that the call is complete. Then check for the status, which is the HTTP status code, value 200 means HTTP is successful. Following is how the method looks,

function processRequest()
{
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
//process the response
}
else
{
alert("
Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
}
}
}

The third step is to process the response received.

The response is stored in responseText of the XMLHttpRequest object. The response is always in the XML form and the object representation of this XML is stored in responseXML
Following code shows how this is done.

of the XMLHttpRequest object. This XML can be parsed in the JavaScript itself using the DOM API to obtain the actual data.
//The method getElementsByTagName, gets the element defined by the given tag
var profileXML
= httpRequest.responseXML.getElementsByTagName("Profile")[0];

//The node value will give you actual data
var profileText
= profileXML.childNodes[0].nodeValue;

Once we get the actual data, now the last step is to update the HTML.

The way to do that is by modifying the DOM (Document Object Model) of the HTML page. This can be done within JavaScript using the DOM API. JavaScript can get access to any element in the HTML DOM and modify it after the HML is loaded. This ability to dynamically modify the HTML DOM object within JavaScript plays very important role in AJAX interaction. The document.getElementById(id) method is used to get reference of the element in DOM. Where id, is the ID attribute of the element you want to modify. In this example the element is DIV with the ID attribute "profileSection".
Following code shows how to modify this DOM element with the data received,

//Create the Text Node with the data received
var profileBody
= document.createTextNode(profileText);

//Get the reference of the DIV in the HTML DOM by passing the ID
var profileSection
= document.getElementById("profileSection");

//Check if the TextNode already exist
if(profileSection.childNodes[0])
{
//If yes then replace the existing node with the new one
profileSection.replaceChild(profileBody, profileSection.childNodes[
0]);
}
else
{
//If not then append the new Text node
profileSection.appendChild(profileBody);
}

How does web page interact with this JavaScript

To tie this interaction with your web page, you need to first identify the part of your web page which will be updated dynamically and mark it with DIV tag and provide it an id, like,

="profileSection">



Identify what event will update the marked area, like clicking on a link, mouseover a image etc. trap this events using JavaScript and call the JavaScript function which creates the XMLHttpRequest object.

What does server side element need to take care of?

While sending the response back the server should set the Content-Type to text/xml, since the XMLHttpRequest object will process this type of request. Also you can set the Cache-Control to no- cache to avoid the browser caching the response locally. The server should always send back data in XML format. The data should be a valid XML format and parse able by the JavaScript. If your data contains characters not friendly with the XML parsers, use the CDATA section in your XML

Author
Kazi Masudul Alam