Want to know what this Ajax stuff is all about?

Well, it is simply making requests to a web server using javascript and receiving the response to a javascript function, and then decide what to do with that response. And all this is achieved using a XmlHttp object.

What is important to note here is that this happens without any refresh on the webpage! In other words you can receive an entirely different web page content from within the current web page without leaving your current page by using Ajax – which is why it is called Asynchronous Javascript.

The below example demonstrates the same where you have following two functions:

sendAjaxRequest which sends an asynchronous request to a given url
getAjaxResponse which receives the response, and in our example displays the received response to the user.

In the sendAjaxRequest function we are first creating a XmlHttp Request object depending on the browser support.
And then we are creating a simple GET request to the given URL by specifying getAjaxResponse as the callback function that needs to be invoked when the Ajax call returns.

Now the callback function getAjaxResponse is called every time the web server makes a response to the GET request and hence in getAjaxResponse we are validating for the final response from the web server where in the requested url content is received. The condition for this is xmlHttp.readyState==4 which means all done and content received.

Please note that this is a very simplified version of an Ajax call and response which assumes that everything else is fine, like the given url is available and the response is properly received from the server and so on. But should be sufficient if you have just started learning Ajax.

var xmlHttp; // The Ajax Object 

//Sends the Ajax Response to the given URL
function sendAjaxRequest(url)
{
  try
  {
      xmlHttp=new XMLHttpRequest();
  }
  catch(e) { // indicates Internet Explorer prior to version 7
    try
     {
       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
     }
     catch(e)
     {
        try
        {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
           alert("Your browser does not support AJAX!");
           return false;
        }
     }
  }
  xmlHttp.onreadystatechange=getAjaxResponse;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
} 

//Receives the Ajax Response
function getAjaxResponse()
{
  if(xmlHttp.readyState==4)//If Ajax Request Completed
  {
  alert(xmlHttp.responseText);//Show response received
  }
}

SocialTwist Tell-a-Friend

Subscribe to HitXP: Be the first to read.
Articles Indian Music Notes Free Software Downloads Kannada