.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Thursday, February 02, 2006

Ajax using Xml Http

These days everybody is talking about Ajax, every product vendor is trying to make their UI products Ajax enabled. Some of the technologies and techniques related to this new buzzword existed for a long time in the form of Remote Scripting (Microsoft), XmlHttp request, etc. Let us here take XmlHttpRequest and examine its features to build our own "Ajax" example. This is how Ajax is defined in Wikipedia...

Asynchronous JavaScript And XML, or its acronym Ajax, is a Web development technique for creating interactive web applications. The intent is to shift a great deal of interaction to the Web surfer's computer, exchanging data with the server behind the scenes, so that the entire Web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page's interactivity, speed, and usability. The Ajax technique uses a combination of:


  • XHTML (or HTML) and CSS for marking up and styling information.
  • The DOM accessed with a client-side scripting language, especially ECMAScript implementations like JavaScript and JScript, to dynamically display and interact with the information presented
  • The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in some situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server. XML is commonly used as the format for transfering data, although any format will work, including preformatted HTML, plain text, JSON and even EBML.

Setup:
I have an ASP.Net page (1.aspx) in my TestApp under http://localhost. What we are trying to do here is to have a listbox and a hyperlink on that page. When you click on that hyperlink, we do a XmlHttp call to server side (without re-posting page) get some data element and paste it to the list box. Simple as that ! In this example, server side is simply passing a text element every time it gets a call. To extend you can use custom query string params to get some keys, go to database, grab some data, format it as xml ( yes it is a requirement ) and pass it to the calling client. Here is the sample code and explanation: ASP.Net page,


<asp:ListBox id="myList" runat="server"> <asp:HyperLink
id="ClickMe" runat="server" NavigateUrl="javascript:clickMe();">Click Me to
Add</asp:HyperLink>



And now paste this javascript code to your page's HEAD section,

var xmlReq=null;
function clickMe(){

var url = "http://localhost/TestApp/1.aspx?x=y";
xmlReq=getXmlHTTP();
if(xmlReq)
{
xmlReq.onreadystatechange = ReadyStateChangeHandler;
xmlReq.open("GET", url, true);
xmlReq.send("");
}


}

function ReadyStateChangeHandler() {

if (xmlReq.readyState == 4) {
// Http "OK"
if (xmlReq.status == 200) {
//do your processing here !
//alert (xmlReq.responseXML.xml);
var str = xmlReq.responseXML.firstChild.text;

var lst = document.getElementById("myList");
var optionObject = new Option(str,str);
var optionRank = lst.options.length;   
lst.options[optionRank]=optionObject;

} else {
alert("Error retreiving data\n" + req.statusText);
}
}
}
function getXmlHTTP(){
if(typeof XMLHttpRequest!="undefined"){
return new XMLHttpRequest();
}
else if(typeof ActiveXObject != "undefined")
{
try{
var xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}
catch(e)
{
return null;
}
}
return null;
}

Now here it needs some explanation, we use a global variable xmlReq to hold the instance of XmlHttpRequest object,
we create that object, call the server side URL with a quesry string element ?X=y to denote it is an XmlHttp call,
and call Send method of XmlHttp object. Notice that we set the call back handler function for onreadystatechange event.

Some of the important properties of XmlHttpRequest are:




























Property
Description
onreadystatechange Event handler for an event that fires at every state change
readyState Object status integer:

0 = uninitialized

1 = loading

2 = loaded

3 = interactive

4 = complete
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
status Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusText String message accompanying the status code


And here is my simple server side code, (for 1.aspx )

private void Page_Load(object sender, System.EventArgs e)
{
if (Request["x"] == "y")
{
Response.ContentType = "text/xml";
Response.Write("" + "Hello from Server Side Code" + "");
Response.End();
}
}


When you run this simple sample, you will see each time you click on that link, a text message "Hello from Server Side Code" will be added to the list/select box. And all this without having to do reload of the page !!!

0 comments: