Sunday, July 22, 2012

Simple AJAX demo

In this article, I would like to give a quick demo of how to code a basic AJAX function.

function ajaxfunction(arguments_if_any){
    if (typeof XMLHttpRequest != "undefined"){
        xmlHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject){
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlHttp == null){
        alert ("Browser does not support XMLHTTP Request");
 return false;
    }

    var url;
     
    url = "/application-name/any-serverside-program";
    url += "?name="+value;
        
    xmlHttp.onreadystatechange = callback-function-name;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return true;    

}

function callback-function-name(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
        /* Stuff to do */
 document.getElementById('id').innerHTML = xmlHttp.responseText;
    }
}


Explanation
  1. First the function 'ajaxfunction' is called during a particular event like clicking a div tag or others.
  2. It checks whether the browser is able to send and receive a XMLHttpRequest object through which asynchronous request and response is achieved.
  3. If the support is available, an asynchronous request is made to a server side script (php/JSP) and once the response is received a 'callbackfunction' is executed.
  4. The third parameter in the open() method, in this case true implies that async is turned ON.
  5. The send() method is useful if we are using POST method - we can send large information using it. Example:- xmlHttp.send("fname=Athi&lname=Ruban");
  6. To assign a stream of HTML from a server output to a div tag we use InnerHtml property.