ASP.NET VERSIONS: ALL
Getting Data with XMLHTTP
By Andrew Flick and Devin Rader
Providing users with a responsive Web user interface has been a consistent problem because of the fact that once a page has been loaded, connection to the server is severed. This causes lengthy trips back to the server, requiring visible postbacks for everything from the simple validation of user information or performing a calculation to obtaining large amounts of data. These postbacks cause the server to rebuild the entire page with new information; the new page is then pushed back to the client.
The result is a Web application that is nowhere near as elegant or fit-and-finish as its Windows Forms counterpart. Starting in Internet Explorer 5.0, Microsoft introduced an ActiveX object known as XMLHTTP. The XMLHTTP object allows the developer, using client-side scripting, to make an HTTP request from the client browser and retrieve data from the server as XML. This gives the developer the capability of dynamically pulling data from the server without requiring a complete page postback. This article will provide you with the knowledge to handle an XMLHTTP request under different browsers, guide you through essential XMLHTTP properties/methods by demonstrating how to make an XMLHTTP request, and then leave you with some potential usage scenarios.
Creating the XMLHTTP Object
This technology and its implementation grew out of Microsoft. When Mozilla and Safari chose to implement it, they established a different route than the one that had been established. Microsoft chose the route of having the developer create a new ActiveXObject with a call to Microsoft.XMLHTTP, which is a part of MSXML. Mozilla and Safari chose the route of having the XMLHTTP object be a default part of the browser:
//Mozilla and Safari
var XMLHTTPReq = new XMLHttpRequest();
var XMLHTTPreq = new ActiveXObject("Microsoft.XMLHTTP");
The W3C has made a recommendation for a standards-based way to implement XMLHTTP as part of their Document Object Model (DOM) Level 3 Load and Save Specification. Currently, however, that is still just a recommendation.
After having the XMLHTTP object, you re now ready to put it to use. It can be used in two manners: getting data and posting data back. This capability allows the developer endless possibilities for a responsive user-interface.
Methods and Properties
The XMLHTTP object exposes a list of methods common to both implementations of the object. These methods do everything from aborting or stopping a current request from processing to transmitting data back to the server. Out of the methods that XMLHTTP object exposes, two methods stand out as being heavily used in many scenarios, open and send:
XMLHTTPReq = new XMLHttpRequest();
XMLHTTPReq.onreadystatechange = processReqChange;
//open(Method, "URL", AsyncFlag)
XMLHTTPReq.open("GET", url, true)
XMLHTTPReq = new ActiveXObject("Microsoft.XMLHTTP");
XMLHTTPReq.onreadystatechange = processReqChange;
XMLHTTPReq.open("GET", url, true);
Note: The above code block demonstrates a very good methodology for getting data from a server as an XMLHTTP request by breaking out code blocks based on the end-user s browser. This code was taken from a great resource site by Apple on using the XMLHttpRequest Object.
The open method is by far one of the most important calls listed in the above function. The first parameter method takes two different methods named GET and POST. These two methods function exactly as expected, with the GET method generally used for receiving data back from the server and the POST method used for sending data to the server. The second parameter holds the URL for where the data is either retrieved or sent. The AsyncFlag is a Boolean value that tells how the method should be run. Its default is set to true, which essentially means any processing will take place directly after the send method is called. If the AsyncFlag is set to false or synchronous, the method will wait for any processing to finish before continuing to run the script. A best practice is to set the AsyncFlag equal to true and handle any code around the onreadystatechange event.
The onreadystatechange event is an extremely useful event when handling XMLHTTP requests because it opens a dialog to a commonly used property: readyState. The readyState property changes during the processing of an XMLHTTP request. There are five states for it listed from 0 to 4: un-initialized, loading, loaded, interactive, complete. Basing your application around the onreadystatechange event gives you a high degree of control over how the processing of the request is handled. In general, however, any computations or utilizations of the returned XML object will require a completion of the transaction, so most processing code will be handled after the readyState is equal to 4:
if(XMLHTTPreq.readyState == 4)
if(XMLHTTPReq.status == 200)
//DO SOME PROCESSING FOR EXAMPLE GRAB AN IMAGE URL FROM AN XML FILE
//GENERATE A NEW IMAGE AND THEN ADD ADDITIONAL CODE TO PLACE IT ON
var XMLChild = XMLHTTPreq.responseXML.documentElement.childNodes(0);
var a = "<<IMG src=" + XMLChild.text + ">>";
Note: The above code block demonstrates a good way to handle the change of readyState. The first check is to make sure the operation is complete and the second check makes sure we have something valid to look at. For instance, a page not found would return a status of 404.
readyState and status are two important properties previously demonstrated; however, two other very important properties are exposed and essential. The responseText property takes the data back as a string, so if you are returning an XML document, you would receive one large string containing everything in the XML document. The other property, responseXML, returns a DOM-compatible object. This is utilized in the above sample to get the text of the first child node in the xml document, which happens to be a URL for an image.
The methods open and send, along with the properties readyState, status, responseXML, and responseText, are commonly used for creating a responsive user-interface for retrieving data back from the server without requiring a full postback.
Potential Usage Scenarios
The potential of XMLHTTP is quite staggering. The implementation is not entirely challenging and thus the usage of this capability has essentially created a de facto standard for creating a responsive Web UI. The idea that we implemented was to fetch images from a server and change through them without reloading the entire page, only making an async request to get the new image. Another potential usage could be exactly like Apple demonstrates in their sample of reading XML data from the iTunes RSS Feed. Another example would be the up and coming Google Suggest.
Google Suggest must maintain some kind of connection back to the server in order to continually update the search with suggested items and search results. This is most likely done using XMLHTTP. One final potential example is to have a datagrid and only load a set amount of data and, as the user scrolls down, fetch more data from the server in the background and populate the grid. These are just a few of the potential capabilities that a developer can achieve by using XMLHTTP.
Using XMLHTTP, you give the end-user a responsive user-interface much closer to the rich experience of a Windows Forms application and the best part is it s fairly easy to accomplish. The Apple site I mentioned above is an excellent resource for learning all the properties and methods that are exposed by the XMLHTTP object and is a great developer resource.
In a future article (in the Whidbey or Visual Studio 2005 timeframe), we ll cover the ASP.NET 2.0 way of doing XMLHTTP, which will be affectionately known as Client Callbacks.
With that, we remind you to e-mail your questions to us at [email protected].
Andrew Flick is a .NET technical evangelist for Infragistics Inc., a Microsoft Visual Studio Industry Partner. He is responsible for authoring reference applications and .NET technology articles, as well as delivering Infragistics technology demonstrations worldwide. Andrew is a Microsoft .NET MVP and is the chair of the INETA Academic Student Committee. Contact Andrew at mailto:[email protected].
Devin Rader is an Infragistics Technology Evangelist and is responsible for authoring Infragistics reference applications and .NET technology articles, as well as the world-wide delivery of Infragistics technology demonstrations. Devin is an active member and leader for INETA, has served as the sole technical editor for numerous works, and is a contributing author for the soon to be published ASP.NET 2.0 Professional. Contact Devin at mailto:[email protected].