Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

AJAX Explained

4.35/5 (42 votes)
17 May 2006CPOL4 min read 1   482  
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.

HTML
<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.

JavaScript
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.

JavaScript
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:

JavaScript
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:

VB
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.

JavaScript
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)