Click here to Skip to main content
15,798,151 members
Articles / Web Development / ASP.NET


Rate me:
Please Sign up or sign in to vote.
4.65/5 (16 votes)
19 Dec 2011CPOL2 min read 61.1K   1.3K   32   24
Using pure AJAX in ASP.NET


I am writing this article because today many developers don't know the basics of AJAX. This article will help you in understanding the basics of xmlHTTPrequest object. The article explain concepts like working of xmlHTTPRequest objects and the flow of data using JavaScript?

I am using a sample project to explain these concepts and trying to achieve output as depicted in the image below:


Using the Code

Download the attached sample code for better understanding. Sample code includes .NET website with two .aspx files; Default.aspx and GetData.aspx. Set the default.aspx as your startup page of the website and run the solution.


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
<head runat="server">
     <script language="javascript" type="text/javascript">
         var xmlHttpRequest;
         function GetData() {
             //create XMLHttpRequest object
             xmlHttpRequest = (window.XMLHttpRequest) ?
	new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");

             //If the browser doesn't support Ajax, exit now
             if (xmlHttpRequest == null)

             //Initiate the XMLHttpRequest object
   "GET", "GetData.aspx", true);

             //Setup the callback function
             xmlHttpRequest.onreadystatechange = StateChange;

             //Send the Ajax request to the server with the GET data
         function StateChange() {
             //0: request not initialized 
             //1: server connection established
             //2: request received 
             //3: processing request 
             //4: request finished and response is ready
             if (xmlHttpRequest.readyState == 4) {
                 var xDoc = StringtoXML(xmlHttpRequest.responseText);
                 document.getElementById('divTable').innerHTML = ConvertToTable(xDoc);
             else {
                 document.getElementById('divTable').innerHTML = 'Loading...';

         function StringtoXML(text) {
             if (window.ActiveXObject) {
                 var doc = new ActiveXObject('Microsoft.XMLDOM');
                 doc.async = 'false';
             } else {
                 var parser = new DOMParser();
                 var doc = parser.parseFromString(text, 'text/xml');
             return doc;
         function ConvertToTable(targetNode) {
             // if the targetNode is xmlNode this line must be removed
             // i couldn't find a way to parse xml string to xml node
             // so i parse xml string to xml document
             targetNode = targetNode.childNodes[0];
             // first we need to create headers
             var columnCount = targetNode.childNodes[0].childNodes.length;
             var rowCount = targetNode.childNodes.length
             // name for the table
             var myTable = document.createElement("table");
             myTable.border = 1;
             myTable.borderColor = "green";
             var firstRow = myTable.insertRow();
             var firstCell = firstRow.insertCell();
             firstCell.colSpan = columnCount;
             firstCell.innerHTML = targetNode.nodeName;
             // name for the columns
             var secondRow = myTable.insertRow();
             for (var i = 0; i < columnCount; i++) {
                 var newCell = secondRow.insertCell();
                 newCell.innerHTML = targetNode.childNodes[0].childNodes[i].nodeName;
             // now fill the rows with data
             for (var i2 = 0; i2 < rowCount; i2++) {
                 var newRow = myTable.insertRow();
                 for (var j = 0; j < columnCount; j++) {
                     var newCell = newRow.insertCell();
                     newCell.innerHTML = 
             return myTable.outerHTML;

    <form id="form1" runat="server">
    <input type="button" name="get" value="Get Data" onclick="GetData();" />
    <div id="divTable">

As you might have observed, that code uses button and div tag. On click event, the button tag needs to populate data from the server using AJAX. This is handled by using a GetData() function of JavaScript. Depending on the browser, a new object of XMLHTTPRequest needs to be created in GetData() function. For IE ActiveXObject and for others, new keyword can be used to instantiate the object. GET or POST method can be used for sending request to the server using XMLHTTPRequest object.

Use Open method to initiate XMLHTTPRequest. There are three parameters; request method, URL, and Variant determines whether the operation is synchronous or asynchronous. Now assign callback function on onreadystatechange event. After completion, send the Ajax request to the server using send method.

StateChange is callback function that will be called when there is state change.

There is a five state change of XMLHTTPrequest Object:

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request finished and response is ready

If xmlHttpRequest.readyState == 4 then we can assume that response is ready and we can use that data. In the above example, the XML string data received is converted to XML object using StringtoXML function and again converted from the XML object to HTML table using ConvertToTable function.


Imports System.Data

Partial Class GetData
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
	Handles Me.Load

        Dim ds As New DataSet()
        Dim dt As New DataTable
        dt.Columns.Add("Name", GetType(String))
        dt.Columns.Add("Age", GetType(String))
        dt.Columns.Add("Org", GetType(String))
        Dim dr As DataRow
        For i As Integer = 0 To 10
            dr = dt.NewRow()
            dr(0) = "Name" + i.ToString()
            dr(1) = "Age" + i.ToString()
            dr(2) = "Org" + i.ToString()
    End Sub

End Class 

This is a blank page with no HTML code. In page load event, the dataset is populated with dummy data. However, in real scenario, dataset should be populated from the database. DataSet.GetXML method will convert the dataset in XML and Response.Write method will write this XML on the page.

Points of Interest

User can use GET or POST method. If user uses GET method, then the parameters can be passed in the URL itself.

//Initiate the XMLHttpRequest object"GET", "GetData.aspx?id=1&all=1", true); 

While using POST method, the parameters needs to be passed in the send method.

//Initiate the XMLHttpRequest object
var param = "id=1&all=1";"POST", "GetData.aspx", true);
//Send the proper header information along with the request
xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttpRequest.setRequestHeader("Content-length", param.length);
xmlHttpRequest.setRequestHeader("Connection", "close");
//Setup the callback function
xmlHttpRequest.onreadystatechange = StateChange;
//Send the Ajax request to the server with the GET data


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Technical Lead iFour Technolab Pvt Ltd
India India
Working with a leading custom software development company, iFour Technolab Pvt. Ltd.

Comments and Discussions

GeneralMy vote of 5 Pin
Debopam Pal4-Dec-13 9:53
professionalDebopam Pal4-Dec-13 9:53 
QuestionReally Good Pin
anrorathod10-May-13 19:01
anrorathod10-May-13 19:01 
AnswerRe: Really Good Pin
Vinod Satapara12-May-13 21:12
Vinod Satapara12-May-13 21:12 
GeneralMy vote of 5 Pin
Monjurul Habib21-Dec-11 7:34
professionalMonjurul Habib21-Dec-11 7:34 
GeneralRe: My vote of 5 Pin
Vinod Satapara21-Dec-11 18:41
Vinod Satapara21-Dec-11 18:41 
GeneralMy vote of 3 Pin
rageit20-Dec-11 3:00
rageit20-Dec-11 3:00 
GeneralRe: My vote of 3 Pin
Vinod Satapara21-Dec-11 18:52
Vinod Satapara21-Dec-11 18:52 
GeneralRe: My vote of 3 Pin
Debopam Pal4-Dec-13 9:36
professionalDebopam Pal4-Dec-13 9:36 
GeneralRe: My vote of 3 Pin
Sinisa Hajnal1-Oct-14 2:39
professionalSinisa Hajnal1-Oct-14 2:39 
GeneralMy vote of 1 Pin
Selvin20-Dec-11 0:19
Selvin20-Dec-11 0:19 
GeneralRe: My vote of 1 Pin
adriancs4-Aug-13 22:32
professionaladriancs4-Aug-13 22:32 
GeneralRe: My vote of 1 Pin
Vinod Satapara7-Aug-13 4:22
Vinod Satapara7-Aug-13 4:22 
GeneralRe: My vote of 1 Pin
adriancs7-Aug-13 4:31
professionaladriancs7-Aug-13 4:31 
Hi, I am replying to Selvin's message. Therefore, you see my message is titled "Re: My vote of 1".
I did not vote 1. It is Selvin vote 1.

You did a good job for posting the information.

By the way, you can consider to add my suggestion for Selvin.

This is supported by Chrome (not tested in FireFox):
<script type="text/javascript">
    function getHtml() {
        try {
            var xhr = new XMLHttpRequest();
  'GET', 'WebForm1.aspx', true);
            xhr.onreadystatechange = function () {
                if (this.readyState !== 4) return;
                if (this.status !== 200) return; // or whatever error handling you want
                document.getElementById('divY').innerHTML = this.responseText;
        catch (err) {
            document.getElementById("divY").innerHTML = err.Message;

GeneralRe: My vote of 1 Pin
Vinod Satapara7-Aug-13 4:38
Vinod Satapara7-Aug-13 4:38 
GeneralRe: My vote of 1 Pin
Debopam Pal4-Dec-13 9:46
professionalDebopam Pal4-Dec-13 9:46 
QuestionGood Pin
KhushaliChauhan19-Dec-11 19:59
KhushaliChauhan19-Dec-11 19:59 
AnswerRe: Good Pin
Vinod Satapara21-Dec-11 18:53
Vinod Satapara21-Dec-11 18:53 
GeneralMy vote of 5 Pin
Nigam Patel19-Dec-11 18:54
Nigam Patel19-Dec-11 18:54 
GeneralRe: My vote of 5 Pin
Vinod Satapara19-Dec-11 19:22
Vinod Satapara19-Dec-11 19:22 
GeneralMy vote of 3 Pin
gstolarov19-Dec-11 14:11
gstolarov19-Dec-11 14:11 
GeneralRe: My vote of 3 Pin
Irwan Hassan21-Dec-11 2:34
Irwan Hassan21-Dec-11 2:34 
GeneralRe: My vote of 4 Pin
gstolarov21-Dec-11 6:07
gstolarov21-Dec-11 6:07 
GeneralRe: My vote of 4 Pin
Irwan Hassan21-Dec-11 6:25
Irwan Hassan21-Dec-11 6:25 
GeneralRe: My vote of 4 Pin
Vinod Satapara21-Dec-11 18:49
Vinod Satapara21-Dec-11 18:49 

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.