Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML
Article

AJAX Explained

Rate me:
Please Sign up or sign in to vote.
4.35/5 (42 votes)
17 May 2006CPOL4 min read 154.4K   480   106   23
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)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalgood job! Pin
chantib30-Mar-07 2:05
chantib30-Mar-07 2:05 
GeneralExcellent work Pin
RichardGrimmer27-Mar-07 2:36
RichardGrimmer27-Mar-07 2:36 
GeneralRe: Excellent work Pin
Tingu Abraham27-Mar-07 12:10
Tingu Abraham27-Mar-07 12:10 
GeneralAjax basics Pin
biaali14-Feb-07 7:04
biaali14-Feb-07 7:04 
Generalgood! Pin
modulesfordnn19-Aug-06 7:10
modulesfordnn19-Aug-06 7:10 
GeneralNice and simple, however... Pin
Member 9619-Jul-06 5:02
Member 9619-Jul-06 5:02 
Questionwhat I'm I doing wrong... Pin
anderslundsgard14-Jun-06 10:23
anderslundsgard14-Jun-06 10:23 
QuestionNeed help Pin
chethana rao12-Jun-06 19:00
chethana rao12-Jun-06 19:00 
GeneralUnknown runtime error at line 45 char 9 [modified] Pin
Dinuj Nath2-Jun-06 19:36
Dinuj Nath2-Jun-06 19:36 
GeneralBriliant Brother Pin
Syed Moshiur Murshed20-May-06 4:29
professionalSyed Moshiur Murshed20-May-06 4:29 
NewsRe: Briliant Brother Pin
Syed Moshiur Murshed20-May-06 5:41
professionalSyed Moshiur Murshed20-May-06 5:41 
GeneralRe: Briliant Brother Pin
Tingu Abraham21-May-06 17:15
Tingu Abraham21-May-06 17:15 
Generaland everybody uses IE (and windows)... Pin
Almighty Bob19-May-06 5:11
Almighty Bob19-May-06 5:11 
GeneralRe: and everybody uses IE (and windows)... [modified] Pin
Tingu Abraham21-May-06 17:13
Tingu Abraham21-May-06 17:13 
GeneralRe: Defining asynchronous Pin
Rajesh R Subramanian18-May-06 22:06
professionalRajesh R Subramanian18-May-06 22:06 
GeneralGood onebut error with XML Pin
Patrick Olurotimi Ige18-May-06 15:37
Patrick Olurotimi Ige18-May-06 15:37 
GeneralRe: Good onebut error with XML Pin
Patrick Olurotimi Ige18-May-06 15:39
Patrick Olurotimi Ige18-May-06 15:39 
sorry
<?xml version="1.0" encoding="utf-8"?>19/05/2006 11:33:38 AM
--------------------------------------^


What you know today isn't enough for tommorow.
GeneralRe: Good onebut error with XML Pin
Morder VonAllem17-Jul-06 12:31
Morder VonAllem17-Jul-06 12:31 
GeneralRe: Good onebut error with XML Pin
sukumar_mca29-Jul-06 11:54
sukumar_mca29-Jul-06 11:54 
GeneralRe: Good onebut error with XML Pin
sukumar_mca29-Jul-06 11:54
sukumar_mca29-Jul-06 11:54 
GeneralRe: Good onebut error with XML Pin
sukumar_mca29-Jul-06 11:55
sukumar_mca29-Jul-06 11:55 
GeneralAnd here is a great AJAX library for ASP.NET Pin
FredericSivignonPro17-May-06 23:35
FredericSivignonPro17-May-06 23:35 
GeneralRe: And here is a great AJAX library for ASP.NET Pin
Tingu Abraham18-May-06 0:43
Tingu Abraham18-May-06 0:43 

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

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