Tech Issues
.NET
.NET FrameWork
ASP.NET FrameWork
Cross Platform
C Sharp
VB.NET
ADO.NET
Managed C++
Remoting
Smart Client
SOAP/XML
Threading
XML Web Services
Windows Services
.NET General
Active Directory
ADO.NET
Applications
ATL Server
BizTalk Server
COM Interop
Compact Framework
Databases
Deployment
Encryption
Exception Handling
Forth .NET
Fortran .NET
GDI+
General
How To
Instrumentation
Internet & Network
J# .NET
MFC/ATL for VC++ 7
MSIL
Office Development
Parsers
Patterns and Practices
Printing
Purgatory
Samples
Security
Unedited Stuff
Utilities
Visual Basic .NET
VS.NET Add-Ins
VS.NET Macros
XAML
ASP.NET
Application
ASP.NET Controls
Caching
Content Management
Custom Controls
Data & Database
Debugging
Design & Architecture
HTML Controls
Images & Multimedia
Reporting
Security
Server Management
Session & Session State
User Controls
Validation
Viewstate
Web Forms
XML/XSL
MS SQL Server
Backup & Recovery
Constraints
Data Types
Design Issues
DTS (Data Transformation)
Full Text Catalog
Functions
Indexing
Job Scheduling
Maintenance
Meta Data Services
Processes
Profiler
Query Analyzer
Replication
Security
Stored Procedures
Support Services
System Databases
Tables
Triggers
T-SQL
Tuning
Views
C#
Algorithms
Applications
Attributes
Beginners
COM / COM+
COM Interop
Computational Geometry
Controls
Data Structures
Database
DataSets, DataGrids etc
Debug and Tracing
Delegates and Events
Design and Architecture
Distributed Apps
Files and Directories
Fuzzy Logic
Games
GDI+
General
Generics
Graphics
How To
Internet
Libraries
Longhorn
Memory Management
Multimedia
Network
Office Programming
Parsers
PInvoke
Printing
Purgatory
Registry
Regular Expressions
Remoting
Samples
Security
Shell Programming
System
Threading
Threads
Unedited Reader Contributions
Utilities
VS.NET Addins
Web Services
Windows Forms
XML/XSLT
Tech >> DOTNET >> ASP.NET

AJAX with ASP.NET

Download source code (6.2 Kb)
By Sudhir Dwivedi

Introduction

AJAX is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.

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  isn't a technology. It's really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

  • standards-based presentation using XHTML and CSS;
  • Dynamic display and interaction using the Document Object Model;
  • Data interchange and manipulation using XML and XSLT;
  • Asynchronous data retrieval using XMLHttpRequest;
  • JavaScript binding everything together.

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.

What is XMLHttpRequest?

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.
The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.

XMLHttpRequest is an important part of the Ajax web development technique, and it is used by many websites to implement responsive and dynamic web applications.
Examples of XMLHttpRequest applications include Google's Gmail service, Google Suggest dynamic look-up interface, Meebo, MSN's Virtual Earth and the MapQuest dynamic map interface.

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.

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

An example to show Server Time without refreshing page

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 div "serverTime" 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)

Build and Run the task

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 "frmServerTime.aspx" page.