Click here to Skip to main content
Click here to Skip to main content

Using AJAX in ASP.NET

, 19 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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

<%@ 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

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.

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

//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)

Share

About the Author

Vinod Satapara
Software Developer (Senior)
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 PinprofessionalDebopam Pal4-Dec-13 9:53 
QuestionImplements ajax in asp.net applications Pinmemberberkut200623-Nov-13 12:02 
QuestionReally Good Pinmemberanrorathod10-May-13 19:01 
AnswerRe: Really Good PinmemberVinod Satapara12-May-13 21:12 
GeneralMy vote of 5 PinmemberMonjurul Habib21-Dec-11 7:34 
GeneralRe: My vote of 5 PinmemberVinod Satapara21-Dec-11 18:41 
GeneralMy vote of 3 Pinmemberrageit20-Dec-11 3:00 
GeneralRe: My vote of 3 PinmemberVinod Satapara21-Dec-11 18:52 
GeneralRe: My vote of 3 PinprofessionalDebopam Pal4-Dec-13 9:36 
GeneralRe: My vote of 3 PinmemberSinisa Hajnal1-Oct-14 2:39 
GeneralMy vote of 1 PinmemberSelvin20-Dec-11 0:19 
GeneralRe: My vote of 1 Pinmvpadriancs4-Aug-13 22:32 
GeneralRe: My vote of 1 PinmemberVinod Satapara7-Aug-13 4:22 
GeneralRe: My vote of 1 Pinmvpadriancs7-Aug-13 4:31 
GeneralRe: My vote of 1 PinmemberVinod Satapara7-Aug-13 4:38 
GeneralRe: My vote of 1 PinprofessionalDebopam Pal4-Dec-13 9:46 
QuestionGood PinmemberKhushaliChauhan19-Dec-11 19:59 
AnswerRe: Good PinmemberVinod Satapara21-Dec-11 18:53 
GeneralMy vote of 5 PinmemberNigam Patel19-Dec-11 18:54 
GeneralRe: My vote of 5 PinmemberVinod Satapara19-Dec-11 19:22 
GeneralMy vote of 3 Pinmembergstolarov19-Dec-11 14:11 
GeneralRe: My vote of 3 PinmemberIrwan Hassan21-Dec-11 2:34 
GeneralRe: My vote of 4 Pinmembergstolarov21-Dec-11 6:07 
GeneralRe: My vote of 4 PinmemberIrwan Hassan21-Dec-11 6:25 
GeneralRe: My vote of 4 PinmemberVinod Satapara21-Dec-11 18:49 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 19 Dec 2011
Article Copyright 2011 by Vinod Satapara
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid