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:
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() {
xmlHttpRequest = (window.XMLHttpRequest) ?
new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
if (xmlHttpRequest == null)
return;
xmlHttpRequest.open("GET", "GetData.aspx", true);
xmlHttpRequest.onreadystatechange = StateChange;
xmlHttpRequest.send(null);
}
function StateChange() {
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) {
targetNode = targetNode.childNodes[0];
var columnCount = targetNode.childNodes[0].childNodes.length;
var rowCount = targetNode.childNodes.length
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;
var secondRow = myTable.insertRow();
for (var i = 0; i < columnCount; i++) {
var newCell = secondRow.insertCell();
newCell.innerHTML = targetNode.childNodes[0].childNodes[i].nodeName;
}
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.
xmlHttpRequest.open("GET", "GetData.aspx?id=1&all=1", true);
While using POST method, the parameters needs to be passed in the send method.
var param = "id=1&all=1";
xmlHttpRequest.open("POST", "GetData.aspx", true);
xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttpRequest.setRequestHeader("Content-length", param.length);
xmlHttpRequest.setRequestHeader("Connection", "close");
xmlHttpRequest.onreadystatechange = StateChange;
xmlHttpRequest.send(param);