|
||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionAJAX 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 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:
Creating the XMLHTTPRequest ObjectThe method of creating the The code presented here first tires to create the object if the browser is Firefox, Safari, or Opera ( function GetXmlHttpObject(handler)
{
var objXmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
catch (e)
{
// Internet Explorer6+ try
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
Methods of the XMLHTTPRequest Object
statechangehandler functionThe function stateChangeHandler()
{
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{
//Gather the results from the callback
var str = xmlHttp.responseText;
//Populate the innerHTML of the div with the results
document.getElementById('nameList').innerHTML = str;
}
if (xmlHttp.readyState == 1)
{
//Populate the innerHTML of the div with the results
document.getElementById('nameList').innerHTML = 'LOADING...';
}
}
xmlHttp_Get functionCreates 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)
{
//Append the name to search for to the requestURL
var url = requestURL + strName;
//Create the xmlHttp object to use in the request
//stateChangeHandler will fire when the state
//has changed, i.e. data is received back
// This is non-blocking (asynchronous)
xmlHttp = GetXmlHttpObject(stateChangeHandler);
//Send the xmlHttp get to the specified url
xmlHttp_Get(xmlHttp, url);
}
else
{
//Textbox blanked out, clear the results
document.getElementById('nameList').innerHTML = '';
}
}
//stateChangeHandler will fire when the state
//has changed, i.e. data is received back
//This is non-blocking (asynchronous)
function stateChangeHandler()
{
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{
//Gather the results from the callback
var str = xmlHttp.responseText;
//Populate the innerHTML of the div with the results
document.getElementById('nameList').innerHTML = str;
}
if (xmlHttp.readyState == 1)
{
//Populate the innerHTML of the div with the results
document.getElementById('nameList').innerHTML = 'LOADING...';
}
}
// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
function GetXmlHttpObject(handler)
{
var objXmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
catch (e)
{
// Internet Explorer try
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 Client and Remote PagesThe 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 “ 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 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"];
//Create the XML-like string to be sent back to the request
string strXmlNames = "";
ArrayList al = new ArrayList();
al = RetreiveNames();
// Copies the elements of the ArrayList to a string array.
String[] arrStrNames = (String[])al.ToArray(typeof(string));
foreach (string strName in arrStrNames)
{
strXmlNames += "<user><name>" + strName + "</name></user>";
}
strXmlNames = "<users>" + strXmlNames + "</users>";
//Create an XmlDocument object to store
//the XML string that we created
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(strXmlNames);
//Create a navigator object to use in the XSL transformation
XPathNavigator xPathNav = xDoc.CreateNavigator();
//Create the XSLTransform object
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(Server.MapPath("Names.xslt"));
//Do the transformation and send the results
//out to the Response object's output stream
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;
}
}
ConclusionIn 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.
|
|||||||||||||||||||||||||||||||||||||||||||||||