AJAX - Old Dog, New Tricks?
I'm so bleeding edge I'm surprised I haven't died from blood loss ... and I just realized it. Back in 1999, Microsoft released a new component as part of their MSXML package called the XMLHTTPRequest object.
This rather oddly (and as it turns out, inaccurately) named COM component was an inspired bit of programming that opened up a socket to a specifed server from Internet Explorer, assigned an event handler to deal with asynchronous responses, let you set up headers, then sent a block of XML (or other resources) back to the server. After a while, the server would get back to you (if you so requested) with a block of text or XML content that you could then use to update something in the client. I actually wrote an article describing this whole process for DevX in 2000.
It's 2005, and all of a sudden AJAX has become the buzzword of the moment. Given the sheer number of such buzzwords at any given time it was easy to assume that it was just another handy marketing term, until a client came in and started talking about needing an AJAX client right now! After a little research to figure out what the heck he was talking about, I discovered my old friend the XMLHTTP pipe, suddenly thrust into fame after years of obscurity.
AJAX is a short-hand term for Asynchronous Javascript And XML. The term was first used by Jesse Garrett of Adaptive Path in the article "AJAX: A New Approach to Web Applications.", in which he discusses the use of the XMLHTTPRequest pipe to interact with the server and generate content on a web client. Anyone he uses Gmail has been using AJAX for some time, even though the developers there didn't realize it. Indeed, much like the notation "Dynamic HTML" was pushed as a way to describe the union of CSS, Javascript, and HTML, AJAX is not so much a technology as a synthesis of technologies - XHTML, Javascript, XMLHTTPRequest and XSLT, all of which have been around (and in many cases working together) - for quite some time.
Damn, I missed my chance to coin a phrase and end up on Wired Magazine! Aaarggh!! Life is not fair!!! Okay, that rant aside, it's probably a good time to go back to asynchronous XHTTPRequest Arch- ... er, AJAX, and look at what it really implies.
Part of the reason for the recent explosion in AJAX as a popular technology has been the fact that about a year ago, after years of stagnation, the browser arena suddenly woke up, and seemingly in lock-step, Opera, Safari and Mozilla Firefox all adopted the XMLHttpRequest object as an inbuilt component with KDE's Konqueror recently joining the ranks. This was a critical turning point, as it meant that at least desktop clients now have the capability of communicating with the server "out-of-band"; browsers for the mobile market aren't quite as far along, but as AJAX enabled web applications become increasingly common, the benefit to incorporate this stack will likely make an XMLHTTPRequest object a required part of any browser, even if its running on a phone.
The XMLHTTPRequest interface varies a little bit between versions (primarily between IE's version and others), but in most cases, runs along the lines of:
var http = new XMLHTTRequest();
http.onload = function(){
var xmlDoc = this.responseXML;
// Do something with xmlDoc
}
http.open("GET","http://myServices.com/serviceX",true);
http.setHeader("ContentType:","text/xml");
http.send(null);
or
pipe.open("POST","http://myServices.com/serviceX",true);
pipe.setRequestHeader("ContentType:","text/xml");
pipe.send(someThing);
The key to this action is the use of the open() method. The first parameter gives the HTTP 1.1 method used for communication - in Mozilla, you're limited (at least in my experience) to the "GET" and "POST" methods, while in IE you can also make additional WebDAV calls such as "PUT" "DELETE" and so forth.
The second parameter is of course the URL of the service that you're communicating with, while the third parameter indicates whether the call is asynchronous (true) or synchronous (false). This distinction is an important aspect of AJAX - while synchronous calls are generally easier to write, asynchronous calls are non-blocking, which in a GUI environment is critical to keeping the interface from appearing unresponsive.
Sending a GET message is generally pretty trivial - you pass the URL with any associated parameters on the query string, then call http.send(null) (http.send() in IE), and wait for the response. Sending a package up to the server is a little more complex: you must invoke the open() method with a "POST" argument, then pass the message or packet as a parameter in the http.send() method, but otherwise it's the same type of operation.
The callback can be a little confusing, especially if you're not that used to working with object Javascript. The above example:
http.onload=function(){
var xmlDoc = this.responseXML;
// do something with xmlDoc
}
makes more sense if you realize that the "this" called here is the instance of the XMLHTTPRequest object that invoked the method in the first place.
Internet Explorer is somewhat limited in its options with regard to the events that it watches, supporting only the onreadystatechange event. This event is called every time the socket changes state from one means of communication to the next via the readystate property, cycling from 0 (uninitialized) through 1 (loading), 2(loaded), 3 (interactive) and 4 (completed). Unless you're building an application that changes visual state as an object is downloading, its generally best to process the event only when the ready state = 4:
http.onreadystatechange = function(){
if (this.readystate == 4){
//process this.
}
}
Mozilla offers more events, including onprogress, onload, and onerror as well as the onreadystatechange. On the flipside, it only supports two result types, retrievable from http.responseText and http.responseXML respectively, while Microsoft also supports http.responseStream for use within non-scripted environments.
AJAX type approaches can range from simple RPC calls in order to pump XHTML content from the server into a document to more sophisticated "push" type applications. The latter model typically employs a polling loop and a message pump - at regular intervals, the HTTPRequest object makes a call to the server to determine if any action changes have occurred (usually by observing changes in event timestamps). When a change does take place, the client then makes a different request against the server for the relevant information. This approach is used in applications such as Google's gmail, as well as numerous web-based RSS readers.
AJAX has existed for some time, though not with the fancy name, but now that most browsers are converging on the utilization of an XMLHTTPRequest object as part of their standard repertoire, AJAX is becoming the tool of choice for web developers trying to simplify their pages OR applications.