Introduction
AJAX is an acronym for Asynchronous JavaScript and XML. It is the latest buzzword amongst web programmers. It is not exactly a new technology, but a combination of several technologies like JavaScript and XML, which allows remote scripting. AJAX creates an asynchronous request to the web server using client-side JavaScript and an XmlHttpRequest
object, and map a function to be executed when the response is received. An asynchronous request means that the browser does not need to wait for the response after sending the request to the server. This creates a responsive user interface without the form being posted back to the server for fetching small amounts of data.
In this article, I will be demonstrating an application of Google Suggest type, in which as a user types text in a textbox, a list of suggestions would be displayed.
This article assumes that the reader has an understanding of ASP.NET, C#, ADO.NET, JavaScript, XML, and XSLT.
The following is an outline of the sequence of events when an ASP.NET AJAX page is rendered:
- Web page is rendered.
- A JavaScript function is executed by a trigger (i.e.,
onKeyUp
, button click etc.). - JavaScript instantiates an
XMLHTTPRequest
object. - The
XMLHTTPRequest
object calls a remote page. - The remote page transforms an XML structure using XSLT and returns the result.
- JavaScript accepts the results and applies it to the page.
- The web page is rendered without a postback to the server by getting the requested data from the remote page.
Creating the XMLHTTPRequest Object
The method of creating the XMLHTTPRequest
object varies from browser to browser. IE implements this object using ActiveX technology, while Firefox, Opera, and Safari implement this as a native object.
The code presented here first tires to create the object if the browser is Firefox, Safari, or Opera (objXmlHttp=new XMLHttpRequest();
). If the browser is not one of these, then it tries to create the object for IE 6 and above (objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
). If the browser is IE6 or earlier, then the object is created as objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
. If the object couldn’t be created, then an alert is displayed saying that the browser doesn’t support AJAX.
function GetXmlHttpObject(handler)
{
var objXmlHttp;
try
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
catch (e)
{
try
{
objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
objXmlHttp.onreadystatechange = handler;
}
catch (e)
{
try
{
objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
objXmlHttp.onreadystatechange = handler;
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
return objXmlHttp;
}
Properties of the XMLHTTPRequest Object
onreadystatechange
- A property of the XMLHTTPRequest
object has been used which is onreadystatechange
. This is the response handler function, which gets called for every change of the readyState
property. readyState
- The state of the receiving request. status
- The HTTP status code returned by the server. responseXML
- The XML document returned by the server.
Methods of the XMLHTTPRequest Object
open
- Initializes a request. send
- Sends a request to the server.
statechangehandler function
The stateChangeHandler
will fire when the state has changed, i.e., data is received back. This is non-blocking (asynchronous).
function stateChangeHandler()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{
var str = xmlHttp.responseText;
document.getElementById('nameList').innerHTML = str;
}
if (xmlHttp.readyState == 1)
{
document.getElementById('nameList').innerHTML = 'LOADING...';
}
}
xmlHttp_Get function
Creates the request and sends it to the server.
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
The complete JavaScript code is as follows:-
var xmlHttp;
var requestURL = 'Names.aspx?q=';
function show_data(strName)
{
if (strName.length > 0)
{
var url = requestURL + strName;
xmlHttp = GetXmlHttpObject(stateChangeHandler);
xmlHttp_Get(xmlHttp, url);
}
else
{
document.getElementById('nameList').innerHTML = '';
}
}
function stateChangeHandler()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{
var str = xmlHttp.responseText;
document.getElementById('nameList').innerHTML = str;
}
if (xmlHttp.readyState == 1)
{
document.getElementById('nameList').innerHTML = 'LOADING...';
}
}
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
function GetXmlHttpObject(handler)
{
var objXmlHttp;
try
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
catch (e)
{
try
{
objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
objXmlHttp.onreadystatechange = handler;
}
catch (e)
{
try
{
objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
objXmlHttp.onreadystatechange = handler;
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
return objXmlHttp;
}
}
The onKeyUp
attribute of the HTML textbox triggers the function named show_data(string)
which invokes the function to send the request to the remote page.
Client and Remote Pages
The client named Default.aspx (can be Default.htm) contains the JavaScript which sends the request to the remote page Names.aspx.
The complete JavaScript is placed in an external script file named AjaxGetNames.js.
The JavaScript request contacts the remote page. The variable “q
” is passed in the query sting to contain the data that the user types in the textbox. An XML string is constructed based on the term. An XSL transform is applied on the XML data.
The ADO.NET code of the remote page queries the Customers table of the Northwind database and finds the names matching the text being typed in the textbox, displaying the suggested names in the div
tag.
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
public partial class Names : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["q"] != null)
{
GetNames();
}
}
private void GetNames()
{
string strQuery = Request.QueryString["q"];
string strXmlNames = "";
ArrayList al = new ArrayList();
al = RetreiveNames();
String[] arrStrNames = (String[])al.ToArray(typeof(string));
foreach (string strName in arrStrNames)
{
strXmlNames += "<user><name>" + strName + "</name></user>";
}
strXmlNames = "<users>" + strXmlNames + "</users>";
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(strXmlNames);
XPathNavigator xPathNav = xDoc.CreateNavigator();
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(Server.MapPath("Names.xslt"));
xslt.Transform(xPathNav, null, Response.OutputStream);
}
public ArrayList RetreiveNames()
{
ArrayList al = new ArrayList();
SqlConnection con = new SqlConnection();
con.ConnectionString =
"Data Source=.;Integrated Security=True;Database=Northwind";
SqlCommand cmd = new SqlCommand("SELECT ContactName from Customers" +
" WHERE ContactName LIKE UPPER('" +
Request.QueryString["q"] + "%')", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
al.Add(rdr[0].ToString());
}
return al;
}
}
Conclusion
In this article, I have demonstrated that AJAX is a technology that employs JavaScript to initiate an asynchronous request to the server and to handle an XML response from the server. A sample ASP.NET application has been demonstrated that uses AJAX to dynamically get a list of names matching those from the database as user types text in the textbox, without requiring the form to post back to the server. In this way, I have illustrated that AJAX allows an ASP.NET web page to provide for a more responsive user interface.