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

Using AJAX in ASP.NET

4.65/5 (16 votes)
19 Dec 2011CPOL2 min read 64.3K   1.3K  
Using pure AJAX in ASP.NET

Introduction

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:

OutputData.png

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.

Default.aspx

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <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)
                 return;

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

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

             //Send the Ajax request to the server with the GET data
             xmlHttpRequest.send(null);
         }
         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';
                 doc.loadXML(text);
             } 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 = 
			targetNode.childNodes[i2].childNodes[j].firstChild.nodeValue;
                 }
             }             
             return myTable.outerHTML;
         }

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

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.

GetData.aspx

VB.NET
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()
            dt.Rows.Add(dr)
        Next
        ds.Tables.Add(dt)
        Response.Write(ds.GetXml())
    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.

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

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

C#
//Initiate the XMLHttpRequest object
var param = "id=1&all=1";
xmlHttpRequest.open("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
xmlHttpRequest.send(param); 

License

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