AJAX - Asynchronous Javascript and Xml


Javascript is a client side language for enhancing web content. Ajax is not so much a language but a method of using javascript to access server side scripts. This means you can use javascript to read/write to a database through those server side scripts. Before the XMLHttpRequest came along, some people used dynamic iframes, but Ajax is a much cleaner way.

AJAX is a generally used in Web 2.0 applications to refresh portions of a webpage but now the whole thing. A simple example of AJAX is
function ajaxtest(){
  url = "/mysite/samplexml.php?a="+encodeURIComponent(123);//server side script
  request = createRequestObject();
  request.open('get', url);
  request.onreadystatechange = function(){
      if(request.readyState == 4 && request.status == 200){
          handleResponse(request);
      }
  }
  request.send(null);
}
function createRequestObject() {
  if(navigator.appName == "Microsoft Internet Explorer")
    return new ActiveXObject("Microsoft.XMLHTTP");
  return new XMLHttpRequest();
}
function handleResponse(request) {
      alert( request.responseText );
      //parse request.responseXML here
}



When you push on the button, it creates a different request object depending on your browser (IE users activex). Then it sets up the request, sets up the onreadtstatechange (callback function to process the response), but the server side request isn't actually made until request.send(null);.

The AJAX request is asynchronous which means that when the request is made, the script doesn't wait for the response at all. However it uses the onreadystatechange function to check periodically if it is done. If readyState=4 and Status=200 then the response has come back successfully and you can parse your response at that point.

The above ajax codeblock was just a quite sample. There are some problems with it. It doesn't automatically escape query parameters in the server side script, it doesn't properly generate the xml request object for older browsers, and it isn't written very well, to integrate with your code.

Check this out.
var AJAX = {
    XMLHttpFactories : [
        function () {return new XMLHttpRequest()},
        function () {return new ActiveXObject("Msxml2.XMLHTTP")},
        function () {return new ActiveXObject("Msxml3.XMLHTTP")},
        function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ],
    createXMLHTTPObject : function ()
    {
        xmlhttp = null;
        for (var i=0;i<AJAX.XMLHttpFactories.length;i++) {
            try {
                xmlhttp = AJAX.XMLHttpFactories[i]();
            }
            catch (e) {
                continue;
            }
            break;
        }
        return xmlhttp;
    },
    objectToURL : function (url,query_str_obj)
    {
           url_str=url + '?';
           for(property in query_str_obj)
               url_str+= property + "=" + encodeURIComponent( query_str_obj[property] ) + "&";
           return url_str;
    },
    execute : function (url, paramsobj, functionCallBack)
    {
        request = new Object();
        request.ajaxRequest = AJAX.createXMLHTTPObject();
        request.sendRequest = function()
        {
            if(request.ajaxRequest.readyState == 1)
            {   //never happen, cause we create a new request each time
                alert('error: still processing previous request');
                return;
            }
            var escapedurl= AJAX.objectToURL(url, paramsobj);
            request.ajaxRequest.open('get', escapedurl);
            request.ajaxRequest.onreadystatechange = function()
            {
                if(request.ajaxRequest.readyState == 4 && request.ajaxRequest.status == 200)
                {
                    //alert(request.ajaxobj.responseText);
                    functionCallBack(request.ajaxRequest);
                }
            }
            request.ajaxRequest.send(null);
        }
        request.sendRequest();
        return request;
    }
};

Usage:
function execute_ajax_function()
{
    var queryparams = {"action": "save", "name":"george foreman"};    
    AJAX.execute( 'abc.php', queryparams , handleResponse);
}
function handleResponse(ajaxRequest)
{
    alert( ajaxRequest.responseText );
    //write code to parse reponse here
    //use ajaxRequest.responseXML or ajaxRequest.responseText
}

While reusable code (the AJAX object) is larger, our implementation specific code is much smaller. The AJAX object is a single unit (and not a bunch of functions) and so it makes a more useful component. It escapes query parameters (the url it would build would be abc.php?action=save&name=george%20foreman. It also takes care of old browsers that support different XMLHttpRequest objects, and takes care of the readyState=4 and readyState=200 stuff for you so you don't have to in your handleResponse code.