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

Using AJAX in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.65/5 (16 votes)
19 Dec 2011CPOL2 min read 62.4K   1.3K   32   24
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)


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 8:53
professionalDebopam Pal4-Dec-13 8:53 
QuestionReally Good Pin
anrorathod10-May-13 18:01
anrorathod10-May-13 18:01 
AnswerRe: Really Good Pin
Vinod Satapara12-May-13 20:12
Vinod Satapara12-May-13 20:12 
GeneralMy vote of 5 Pin
Monjurul Habib21-Dec-11 6:34
professionalMonjurul Habib21-Dec-11 6:34 
GeneralRe: My vote of 5 Pin
Vinod Satapara21-Dec-11 17:41
Vinod Satapara21-Dec-11 17:41 
GeneralMy vote of 3 Pin
rageit20-Dec-11 2:00
rageit20-Dec-11 2:00 
GeneralRe: My vote of 3 Pin
Vinod Satapara21-Dec-11 17:52
Vinod Satapara21-Dec-11 17:52 
Thanks for your comment. My target audience for this article is freshers who are starting development using AJAX. It will be useful for the beginners not for the advance developers.
GeneralRe: My vote of 3 Pin
Debopam Pal4-Dec-13 8:36
professionalDebopam Pal4-Dec-13 8:36 
GeneralRe: My vote of 3 Pin
Sinisa Hajnal1-Oct-14 1:39
professionalSinisa Hajnal1-Oct-14 1:39 
GeneralMy vote of 1 Pin
Selvin19-Dec-11 23:19
Selvin19-Dec-11 23:19 
GeneralRe: My vote of 1 Pin
adriancs4-Aug-13 21:32
mvaadriancs4-Aug-13 21:32 
GeneralRe: My vote of 1 Pin
Vinod Satapara7-Aug-13 3:22
Vinod Satapara7-Aug-13 3:22 
GeneralRe: My vote of 1 Pin
adriancs7-Aug-13 3:31
mvaadriancs7-Aug-13 3:31 
GeneralRe: My vote of 1 Pin
Vinod Satapara7-Aug-13 3:38
Vinod Satapara7-Aug-13 3:38 
GeneralRe: My vote of 1 Pin
Debopam Pal4-Dec-13 8:46
professionalDebopam Pal4-Dec-13 8:46 
QuestionGood Pin
KhushaliChauhan19-Dec-11 18:59
KhushaliChauhan19-Dec-11 18:59 
AnswerRe: Good Pin
Vinod Satapara21-Dec-11 17:53
Vinod Satapara21-Dec-11 17:53 
GeneralMy vote of 5 Pin
Nigam Patel19-Dec-11 17:54
Nigam Patel19-Dec-11 17:54 
GeneralRe: My vote of 5 Pin
Vinod Satapara19-Dec-11 18:22
Vinod Satapara19-Dec-11 18:22 
GeneralMy vote of 3 Pin
gstolarov19-Dec-11 13:11
gstolarov19-Dec-11 13:11 
GeneralRe: My vote of 3 Pin
Irwan Hassan21-Dec-11 1:34
Irwan Hassan21-Dec-11 1:34 
GeneralRe: My vote of 4 Pin
gstolarov21-Dec-11 5:07
gstolarov21-Dec-11 5:07 
GeneralRe: My vote of 4 Pin
Irwan Hassan21-Dec-11 5:25
Irwan Hassan21-Dec-11 5:25 
GeneralRe: My vote of 4 Pin
Vinod Satapara21-Dec-11 17:49
Vinod Satapara21-Dec-11 17: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.