Ajax Working

Working of Ajax

Step1: We need to write code in the browser using JavaScript.
Step2: Create the XML HttpRequest object to communicate with the server without refreshing the page.
Step3: The JavaScript code in the browser reads, processes and updates, the data which comes back from the server which is XML or plain text.

Creating XMLHttpRequest Object

Syntax:
variable = new XMLHttpRequest ( );

Example : Create XMLHttpRequest Object

var Xhttp;
if(window.XMLHttpRequest )
{
    Xhttp = new XMLHttpRequest ();
}
else
{
    xhttp = new ActivxObject (“Microsoft.XMLHTTP” );
}

Sending a request to a Server

To send a request to a server, we can use the open() and send () methods.

Syntax

xHttp.open (“GET”, “ajax_info.txt”, true);
xhttp( );

Server Response

  • To get the response from a server, we can use the responseText or responseXML property of the XMLHttp request.
  • Server responseText property: We can use this property, if the response from the server is in plain text.
  • Server responseXML Text Property: We can use this property, if the response from server is XML.

Example : Sending a request to a Server and getting server response.

<HTML>
<HEAD>
     <SCRIPT LANGUAGE="JavaScript">
     var XHobj = false;
     if (window.XMLHttpRequest)
     {
          // code for IE6,IE5,Google chrome, Firefox Web Browser
          XHobj = new ActiveXobject("Microsoft.XMLHTTP);
     }
     else if(window.ActiveXObject)
     {
          //code for IE6,IE5
          XHobj = new ActiveXobject("Microsoft.XMLHTTP");
          function fetchdata(datasource.divID)
          {
               if(XHobj)
               {
                    XHobj.open("GET", datasource);
                    XHobj.onereadystatechange=function()
                    {
                         if(XHobj.readyState==4 && XHobj.status==200)
                    }
                    document.getElementById(divID).innerHTML=Xobj.responseText;
               }
          }
          Xobj.send(null);
     }
     </SCRIPT>
</HEAD>
<BODY>
     <h3>Welcome to AJAX</h3>
     <FORM>
     <INPUT TYPE=button value="Fetch Message" onclick="fetchdata ('info.txt','myDiv')">
     <div id="myDiv"><b>AJAX applications are browser and platform independent.:</b></div>
</BODY>
</HTML>


In the above example AJAX uses XMLHttpRequest object to communicate with the server behind the scenes and we have created variable XHobj for this object.
Var Xobj = false;
This variable is created false, so the script can check later whether the variable was indeed created.

Output:

working of ajax  

AJAX is not used independently, but it works with javascript, XHTML, CSS and XML.