Ajax · JavaScript · Programming

Ajax Code Pattern

It is no longer fashionable to write your own custom to send or receive Ajax requests what with so many great frameworks providing all the functionality. However, knowing the basics of a technology should never hurt anyone.

So here we present the code pattern that is used in almost all the ajax code.

1. Create xmlhttprequest object

function getXMLHttpObject() {
    if(window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return new ActiveXObject("MicroSoft.XMLHTTP");

2. Create the response handler callback function.

function callbackFunction (xmlHttpObj) {
    //application logic

3. Set the onreadystatechange property of the XMLHttpRequest object to a callback function handling the server response.

var req = getXMLHttpObject();

req.onreadystatechange = callbackFunction;

4. Send request typically Get or Post.

4a. Send Get Request

function sendGet(url) {

4b. Send Post Request

function sendPost(url,params) {

4c. When a request is sent the xmlHttpRequest goes through the following states:

xmlHttpRequest.readyState = 0;//UNSENT 
xmlHttpRequest.readyState = 1;//OPENED 
xmlHttpRequest.readyState = 2;//HEADERS_RECEIVED
xmlHttpRequest.readyState = 3;//LOADING 
xmlHttpRequest.readyState = 4;//DONE 

4d. On readyState = 4 :

req.status     = HTTP status code like 200, 404, 500 etc.
req.statusText = HTTP status text.

5. Handle the server response.

function callbackFunction () {
    if (req.readyState == 4) {
        if (req.status == 200) {
            //Application logic to process req.responseXML or req.responseText
        } else {
            //application logic to handle the Error.

Sample responseXML/responseText callback function

XML Format

<?xml version="1.0"?>
        <title>Three Idiots</title>
function callbackFunction() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            //success case
            var resXML = req.responseXML; //get the XML from reqquest object
            var resTxt = req.responseText; //get the responseText
            uaStr = navigator.userAgent.toLowerCase();

            // Firefox has issue reading the xml returned from server
            if (window.DOMParser) {
                var parser = new DOMParser();
                resXML = parser.parseFromString(resTxt, "text/xml");

            //get the root node
            var rootNode = resXML.documentElement;
            var movies = rootNode.getElementsByTagName('movie');
            //iterate over the XML nodes
            for (var i=0; i<movies.length; i++)
                var movie = movies[i];
                var title = movie.getElementsByTagName('title')[0].firstChild.nodeValue;
                var year = movie.getElementsByTagName('year')[0].firstChild.nodeValue;

        } else {
            //handle the Error.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s