Introduction to AJAX

Saturday 23 April 2011 Posted by Sridharan Natarajan
AJAX is an acronym for Asynchronous JavaScript and XML and it is a technique that allows the web pages to be updated asynchronously without refreshing the entire page. It gives better user experience, interactive web pages and seamless server communication.

You can implement AJAX in the following way:

1. Create XMLHttpRequest object
    AJAX uses the XMLHttpRequest object to exchange data asynchronously with  the web server. This XMLHttpRequest object is having the following states:
readyState Status Codes:
0 = uninitialized (Request to the server is not initialized)
1 = loading (Connection to the server is established)
2 = loaded (Request to the server has been loaded)
3 = interactive (Request is in process)
4 = complete (Response is processes and the response is sent)
This state is called readyState.This is the important property of the XMLHttpRequest object.

The readyState 4 means, the request has been processed and the response is received.

2. Define a call back function that will be called whenever the state of the XMLHttpRequest object is changed. The event is called onreadyStateChanged.
Status is an another important property that holds the status of the response returned from the server.
Ex.
200: "OK"
404: Page not found

3. Send the request.

4. Most importantly the responseText/responseHTML holds the actual body of the response.  This can be displayed in any part of the web page.

Now we will see how to implement the above steps.
<html>
<head>
<script type="text/javascript">

//This creates XMLHttpRequest for various browsers
function getXMLHttpReqObject(){
  var xmlhttp = null; 
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
  return xmlhttp;

}

function getEmpName(){
  var empId = document.getElementById("getEmpName").value;
  var xmlhttp = getXMLHttpReqObject();

  if(xmlhttp != null){
     xmlhttp.onreadystatechange = displayName;
     xmlhttp.open("GET","getEmpName.php?empId=" + empId,true);
     xmlhttp.send();

  }

}

//this is the callback function that will be called whenever the readystate is changed.
function displayName(xmlhttp){
  
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    document.getElementById("empName").innerHTML = xmlhttp.responseText;
  }
  
} 

</script>

</head>

<body>
   <form>
     Enter Emp Id <input type="text" name="empId" value="" /> &nbsp;
<input type="button" name="getEmpName" id="getEmpName" value="Get Emp. Name" onClick="getEmpName();"/> </br>
Employee Name: <span id="empName"></span>
   </form>
</body>

</html>

Labels:
  1. Useful Blog !! Good KT Sridhar !!

Post a Comment