Making AJAX call using smiple XMLHTTPRequest Object

This Article will explain how to make simple AJAX call from JSP 

Follow the simple Steps 
a.         Create a servlet (can be any server side component that listen to requests and respond back like JSP or PHP).
b.       In JSP file, first get the XMLHttpRequest object (it is different for different browsers)
c.         onreadystatechange property: After a request send to a server, we need a function to receive the data returned from the server. The onreadystatechange property stores the function that will process the response from a server. The function is stored in the property to be called automatically.
xmlhttp.onreadystatechange=function()
{
// We are going to write some code here
}
d.        readyState property: The readyState property holds the status of the server's response each time the readyState property changes, the onreadystatechange function will be executed .Possible values for readyState property are
i           0 – request is not intialized
ii         1 – request has been setup
iii        2 – request has sent
iv       3 – request in progress
v         4 – request is completed
e.        To send off a request to the server, we use the open() and send() methods.
i           Open(): The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously(true – asynchronous , false – synchronous )
ii         Send: The send() method sends the request off to the server.
f.          Sample is as follows
//getting XMLHttpRequest Object
function getXMLHTTPObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
if(typeof XMLHttpRequest != 'undefined'){
   return new XMLHttpRequest();
}else{
  try{
  return new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
  try{
          return new ActiveXObject("Microsoft.XMLHTTP");
  }catch(e){}
  }
}
 return false;
}
//make AJAX call
function invokeAjax(){
       xmlHTTP=getXMLHTTPObject();
       var ajaxServletURL="<%=response.encodeUrl(request.getContextPath())%>"+"/SivaAjaxServlet?name=siva";
       xmlHTTP.open("POST",ajaxServletURL,true);
       xmlHTTP.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
       xmlHTTP.onreadystatechange=httpResponse;
       xmlHTTP.send(null);
}
 //callback method
function httpResponse(){
  if(xmlHTTP.readyState==4){
    document.getElementById("ajaxdiv").innerHTML=xmlHTTP.responseText;
  }
}
 //simple html elements gets change after ajax call
<div id="ajaxdiv">
 <table>
       <tr><td>Loading ....Ajax example</td><td><input type="button" onClick="invokeAjax()" name="but1" value="submit"/></td></tr>
 </table>
</div></div>


No comments:

Post a Comment