Click here to Skip to main content
Click here to Skip to main content

AJAX Explained

, 17 May 2006
Rate this:
Please Sign up or sign in to vote.
An introduction to AJAX for ASP.NET applications.

Introduction

AJAX is not a programming language, nor is it a new technology. AJAX has been technically available since the inclusion of the XMLHttpRequest component (which is a part of MSXML) in Internet Explorer 5.0. Now, that dates back to the year 1999. But the word “AJAX” is all new. AJAX stands for “Asynchronous JavaScript and XML”, and was coined by Jesse James Garrett, founder of Adaptive Path.

AJAX relies on XMLHttpRequest, CSS, DOM, and other technologies. The main characteristic of AJAX is its “asynchronous” nature, which means it can send and receive data from the server without having to refresh the page. Yes, you heard me right...without having to refresh the page.

So what is asynchronous?

In a traditional web page, when a user sends a request (like clicking on a Submit button), the user waits until the page gets reloaded. During the normal wait period, which ranges from anywhere between a few seconds to “ages”, the user would be presented with a blank browser screen to stare at. In asynchronous mode, the client and the server will work independently and also communicate independently, allowing the user to continue interaction with the web page, independent of what is happening on the server.

And what about JavaScript?

Now, here lieth the secret. JavaScript is used to make the asynchronous request to the server. Once the response is received from the server, JavaScript is used to modify the content of the page displayed to the user, to show that the user-initiated action was successful.

And XML?

The data that is sent asynchronously from the server to the client, is packaged in an XML format, so it can be easily processed by JavaScript. Though generally the data is sent to the client in XML format, it can also be sent in a lot of other formats (like simple text).

There’s nothing really new about AJAX. Normally, we make a request, and receive a page as the response. This is how the web works already — the only difference is that now we can make these requests from JavaScript.

Let me show you an example

Let's begin with a simple example of getting the server's time and displaying it on the page using AJAX. In this example, just to make things a little less complicated, we would be using text to send the data from the server to the client, instead of XML. Create a new ASP.NET web application. Create a new WebForm, and rename it "ClientServerTime.aspx". Add this piece of code inside the <body> of the page.

<form name="frmServerTime" id="frmServerTime">
    <table border="0" cellpadding="4" cellspacing="0" id="Table2"> 
        <tr>                    
            <td><input type="button" name="btnTime" 
                 value="Show Server Time" id="btnTime" 
                 onclick="showServerTime();"></td> 
        </tr> 
        <tr>                    
            <td><div id="serverTime"></div></td> 
        </tr> 
    </table> 
</form>

This contains a divserverTime” that would be used to display the time from the server. showServerTime is the function that will be called when you click on the button. This function would contain the code to retrieve the server's time and display it.

To get the entire thing to work, first we need to create a request object.

xmlHttp = new ActiveXObject('Msxml2.XMLHTTP'); 
//Send the xmlHttp get to the specified url 
xmlHttp.open('GET', url, true);

The xmlhttp.open is used to specify the page you are using to send the request. We are using GET in this case, instead of POST, because we are just getting some value from the server.

Next, we need to have a callback function that will wait until the response is sent from the server.

if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{ 
    //Gather the results from the callback 
    var str = xmlHttp.responseText;
}

readyState = 4 or ‘complete’ means that the response is complete, and we can proceed with what we want to do with the data received.

Take a look at the complete script. Add this inside your <script> tags:

var xmlHttp; 
var requestURL = 'getServerTime.aspx';                        
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;

function showServerTime()
{             
    //Append the name to search for to the requestURL 
    var url = requestURL;
            
    var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
    
    xmlHttp = new ActiveXObject(strObjName);                                 
    xmlHttp.onreadystatechange = CallBackHandler;
            
    //Send the xmlHttp get to the specified url
    xmlHttp.open('GET', url, true); 
    xmlHttp.send(null);                        
    
} 

// This function will be called when the state
// has changed, i.e. when data is returned from the server
function CallBackHandler() 
{ 
    // State of 4 or 'complete' represents that data has been returned 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){ 
        //Gather the results from the callback 
        var str = xmlHttp.responseText; 
        
        //Populate the innerHTML of the div with the results 
        document.getElementById('serverTime').innerHTML = str; 
    } 
}

Create another WebForm and remove all the lines in the .aspx page except the Page directive. Rename the WebForm "getServerTime.aspx". On the code-behind (getServerTime.aspx.vb), add the following line in the Page_Load function:

Response.Write(Date.Now.ToString)

We are done

Build the project and run it. When the button is clicked, it would display the time from the server without refreshing the page.

Note that subsequent clicks after the first click would not display the correct time. This is because the page is getting cached. To overcome this, you need to add a little query string to your requestURL in the showServerTime function.

var url = requestURL + ‘?q=’ + Math.random();

Source code

You could download the source code using the link at the top of this page. In the source code, data from the server is returned in XML format, instead of the simple text that was returned in the above example. This requires inclusion of an extra page "ServerTime.xslt" which is used as the XML transformation file. You would have to create a new ASP.NET application, add these files into the project, build it, and run the "PageServerTime.aspx" page.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Tingz Abraham

United States United States
When Tingz Abraham was old enough to realize that computers were going to invade the world, he decided to pursue a career that would keep him close to computers. That landed him a job as an IT Solutions Consultant in Seattle, USA where he currently works. He believes he can program in many languages, including English. Ctrl+C and Ctrl+V are his favorite keys on the keyboard.
 
After he found he sucked real bad at playing the violin, he just stuck to the guitar and piano. He has a ravishing need for speed and takes a fancy to anything with wheels, including his black Mustang which he's aptly named 'Tingzmobile'.
 
At work you can constantly hear him say - "Oh! The things I learn after I know it all!" He keeps himself very busy, and in his spare time he keeps wondering why '24 hours a day is just not enough'.
 
He exists at www.Tingzabraham.com

Comments and Discussions

 
Generalgood job! Pinmemberchantib30-Mar-07 2:05 
GeneralExcellent work PinmemberRichardGrimmer27-Mar-07 2:36 
GeneralRe: Excellent work PinmemberTiNgZ aBrAhAm27-Mar-07 12:10 
GeneralAjax basics Pinmemberbiaali14-Feb-07 7:04 
Generalgood! Pinmemberaevina.com19-Aug-06 7:10 
GeneralNice and simple, however... PinmemberJohn Cardinal19-Jul-06 5:02 
Questionwhat I'm I doing wrong... Pinmemberd00_ape14-Jun-06 10:23 
QuestionNeed help Pinmemberchethana rao12-Jun-06 19:00 
GeneralUnknown runtime error at line 45 char 9 [modified] PinmemberDinuj Nath2-Jun-06 19:36 
GeneralBriliant Brother PinmemberSyed Moshiur Murshed20-May-06 4:29 
NewsRe: Briliant Brother PinmemberSyed Moshiur Murshed20-May-06 5:41 
GeneralRe: Briliant Brother PinmemberTiNgZ aBrAhAm21-May-06 17:15 
Generaland everybody uses IE (and windows)... PinmemberMadHatter ¢19-May-06 5:11 
GeneralRe: and everybody uses IE (and windows)... [modified] PinmemberTiNgZ aBrAhAm21-May-06 17:13 
GeneralRe: Defining asynchronous PinmemberRajesh R. Subramanian18-May-06 22:06 
GeneralGood onebut error with XML PinmemberPatrick Olurotimi Ige18-May-06 15:37 
GeneralRe: Good onebut error with XML PinmemberPatrick Olurotimi Ige18-May-06 15:39 
GeneralRe: Good onebut error with XML Pinmemberbendornis17-Jul-06 12:31 
GeneralRe: Good onebut error with XML Pinmembersukumar_mca29-Jul-06 11:54 
GeneralRe: Good onebut error with XML Pinmembersukumar_mca29-Jul-06 11:54 
GeneralRe: Good onebut error with XML Pinmembersukumar_mca29-Jul-06 11:55 
GeneralAnd here is a great AJAX library for ASP.NET PinmemberFrederic Sivignon17-May-06 23:35 
GeneralRe: And here is a great AJAX library for ASP.NET PinmemberTiNgZ aBrAhAm18-May-06 0:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 17 May 2006
Article Copyright 2006 by Tingz Abraham
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid