Web Development

See how the XMLHttpRequest object is the heart and soul of AJAX

Here's an example that demonstrates the elegance and simplicity of using the XMLHttpRequest object. Tony Patton also explores how the XMLHttpRequest object opens the door to many other uses that can improve the user experience.

Web developers' common complaint with browser-based applications is its stateless nature. That is, once data is requested and delivered from a server, the connection is lost; any subsequent data requests require a new connection. While there are various ways to cache data on the client side via cookies or with proprietary technologies like ASP.NET, the XMLHttpRequest object offers a standards-based approach to reduce response time.

XML in the browser

The XMLHttpRequest object is the crux of the AJAX (Asynchronous JavaScript + XML) development paradigm, but we can hardly consider it new. Microsoft first implemented the XMLHttpRequest object in IE 5 for Windows as an ActiveX object. The Mozilla project implemented a compatible native version for Mozilla 1.0 (and Netscape 7), with Apple joining the fray in Safari 1.2. Its inclusion in the W3C's DOM specification makes it a standard for Web development.

Weekly development tips in your inbox
Keep your developer skills sharp by signing up for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday.
Automatically sign up today!

The XMLHttpRequest object allows JavaScript to make HTTP requests without reloading a page. In essence, HTTP requests are made with responses received in the background, while the user continues to work—completely unaware of the background processing since there are no visible interruptions. This is a godsend to developers, resulting in a response user interface with the ability to ferry data to the server in real time.

Methods

The XMLHttpRequest object contains a small number of methods, as I outline below:

  • abort(): Stops the current request.
  • getAllResponseHeaders(): Returns a string that contains the complete set of header labels and values.
  • getResponseHeader("name"): Returns the string value for the specified header label.
  • open("method", "url", asyncflag, "username","password"): Performs setup functions for an upcoming request, and allows you to designate the URL, method (usually get or post), and optional parameters for the async flag, username, and password.
  • send(content): Transmits the request (set up by the open method). The optional content parameter may contain string or DOM formatted data.
  • setRequestHeader("label", "value"): Allows you to assign label/value pairs to be sent with a request (via the send method).

The optional third parameter of the open method is a Boolean value that controls whether you should handle the upcoming transaction asynchronously; this is where the asynchronous portion of the AJAX acronym enters the picture. The default behavior (true) is to act asynchronously, which means that script processing carries on immediately after invoking the send() method without waiting for a response. If you set this value to false, however, the script waits for the request to be sent and for a response to arrive from the server.

Properties

Network or server issues may cause problems that result in a script hanging, so waiting for a response before continuing processing is not always the best idea. It is safer to send asynchronously and design your code around the onreadystatechange event for the request object, as outlined in the following list of properties of the XMLHttpRequest object:

  • onreadystatechange: Event handler for an event that fires at every state change.
  • readyState: The status of the object (0 = unitialized, 1 = loading, 2 = loaded, 3 = interactive, 4 = complete).
  • responseText: A string representation of the data returned by the server.
  • responseXML: The DOM representation of the data returned by the server.
  • status: The numeric code for the server request—the HTTP status code.
  • statusText: The string message accompanying the numeric status code.

Using the XMLHttpRequest object's methods and properties, you can send requests in the background, while the user continues to use the application.

See the object in action

There are two ways to utilize the XMLHttpRequest object in your JavaScript code. Here's the IE approach:

varreq = new ActiveXObject("Microsoft.XMLHTTP");

and here's the non-IE approach:

varreq = new XMLHttpRequest();

For this reason, you may want to include code to create an object instance based on the browser you're using, as the following code demonstrates:

if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}

This creates an instance of the XMLHttpRequest class based upon the browser. The code to put the object to work is the same after the object is instantiated.

In Listing A, the Web page uses ASP.NET to perform a telephone number lookup for a company name entered in the text box (I used the standard SQL Server Northwind database). The text field's JavaScript onblur event triggers the lookup.

A few notes on the HTML page:

  • The getTelephone JavaScript method handles working with the XMLHttpRequest object. It creates the object (depending on the browser), and posts the value passed to it (from text field) to the ASP.NET page.
  • The return value of the XMLHttpRequest object (responseText property) is used to determine if no data or an error was returned.
  • The text field's onblur event ties it to the JavaScript function, which is called when the user tabs or clicks off the field.

The XMLHttpRequest object calls the ASP.NET code in Listing B. The ASP.NET page is simple; it uses the value passed to the page via the QueryString variable to locate matching data in the SQL Server database and then return either the matching data or an error if an exception is encountered.

This example uses a backend ASP.NET page, but it could use any development language. In addition, the backend page does not have to use the same development language or platform as the page calling it since it is simply using the returned data. The backend page could be a Web service as well.

Staying connected

The example demonstrates the elegance and simplicity of using the XMLHttpRequest object, which also opens the door to many other uses that can improve the user experience. A few of the many other applications include the following:

  • Save data instantly without clicking a button.
  • Instant shopping cart management allows items to be added, removed, or edited.
  • Bring server-side data validation to the browser.
  • Translate a word as it is typed.

More to come

While this week's example demonstrated the basics of the heart and soul of the AJAX approach—the XMLHttpRequest object—next week we will dive further into AJAX and the XMLHttpRequest object by returning and utilizing XML-formatted data.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

Miss a column?

Check out the Web Development Zone archive, and catch up on the most recent editions of Tony Patton's column.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

0 comments

Editor's Picks