Here the article explains how to implement AJAX using JavaScript using a simple example which gets the Server Current Time. This example demostrates the use of tradional AJAX techniques thus helping us to understand how all AJAX applications and components in today's world work


Create the XML HTTP Request Object


xmlhttp=null;


if (window.XMLHttpRequest)

{

      // code for all new browsers

xmlhttp=new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

      // code for IE5 and IE6

      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");             

}



Prepare and send the Request

While preparing the request you will need to specify the function which should be invoked when the state of the xmlhttp object changes below state_Change function will be called.

Then open will open the connection with the server.


xmlhttp.onreadystatechange=state_Change;

xmlhttp.open("GET","Default.aspx?GetTime=true",true);

xmlhttp.send(null);


Server Side Accepting the Request

The Request is Received Server Side it is processed and the Response is sent back.

 C#

Response.Cache.SetCacheability(HttpCacheability.NoCache);    

if (Request.QueryString["GetTime"] == "true")

{

    Response.Clear();

    Response.Write(DateTime.Now.ToShortTimeString());

    Response.End();

}


VB.Net

Response.Cache.SetCacheability(HttpCacheability.NoCache)

If Request.QueryString("GetTime") = "true" Then

Response.Clear()

Response.Write(DateTime.Now.ToShortTimeString())

Response.End()

End If


Note that in both C# and VB.Net I am using the following statement


Response.Cache.SetCacheability(HttpCacheability.NoCache)


The above statement I necessary since if it is not there request is sent to the server only for the first time and after that it is not since the page has been cached by Browser.

To avoid that the above statement prevents the page from being cached and the request is sent to the server each time.


Receiving the Response

As soon as the Response is sent back to the client page the state_Change function is invoked

This function accepts the Response and displays the time on the page.


function state_Change()

{

    if (xmlhttp.readyState==4)

    {// 4 = "Response loaded"


        if (xmlhttp.status==200)

        {// 200 = Response Error Free               

          var lblMesg = document.getElementById("<%=lblMsg.ClientID%>");

          lblMesg.innerHTML = "Server Time is : " + xmlhttp.responseText;

        }

        else

        {

            alert("Problem retrieving XML data");

        }

    }

 }


The above code has been tested in the following Browsers  

1. Internet Explorer 7

2. Firefox 3

3. Google Chrome

You can download the source code in VB.Net and C# here.

XMLHTTP.zip (3.63 kb)