AJAX - beyond the buzzwords


by Trevor Lowing
Download article source.

Since Google decided to use SOAP/XMLHTTP for their new map interface the geek web has been flooded with AJAX articles. Here I will discuss the importance of AJAX (Asynchronous JavaScript And XML) as well as some of the tradeoffs developers will encounter if they choose to use this technology. More importantly, I have also posted a version of this article with a running demo on my website (recommended). You can also download the article source and try it for yourself.

AJAX is a less than informative name for combining DHTML(JavaScript & HTML) and XML technologies to create fancier web interfaces. Wikipedia gives a decent definition for AJAX but I would describe it thus: Traditional web applications squirt out serial HTML strings to produce web pages, refreshing the entire page every time a user clicks a link or button. AJAX pinpoints only the information on a page that needs to be changed and gets the new information in the background. So ,regardless of who coined the term AJAX, it is a technique we will see employed more often.

Before AJAX, web developers resorted to various techniques (hacks) to pass bits of information back and forth with the server to update a page. One popular technique was to request pages within hidden IFrame or Frame elements that could then be accessed using JavaScript. Another was to popup a window that requested the updated data and wrote it back to the parent(opener) window. Developers also used hidden form fields and IE inline XML to store additional information on the client. In short, developers came up with many techniques to achieve what AJAX achieves to elegantly.

One of the core technologies behind AJAX is the XMLHTTP Request object - think of it as a tiny hidden web browser. The XMLHTTPRequest method was actually pioneered by Microsoft in IE4 for their Outlook Web Access email client software. When a user interacts with a page this tiny browser requests, in the background, just the information needed. Another technology, the XML Document Object Model (DOM), allows the developer to treat each page as a tree with branches and leaves that are easily added or changed.

//create the XMLHttpRequest object function loadXMLFile(url) { if (window.ActiveXObject) {//IE xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); if (xmlhttp) { xmlhttp.onreadystatechange=xmlhttpReady; xmlhttp.open("GET",url,true); xmlhttp.send(); } } else if (window.XMLHttpRequest) {// code for Mozilla, Safari, etc xmlhttp=new XMLHttpRequest(); xmlhttp.preserveWhitespace = false; xmlhttp.onreadystatechange=xmlhttpReady; xmlhttp.open("GET",url,true); xmlhttp.send(null); } } //wait for the XML document to load and update the page function xmlhttpReady() { if (xmlhttp.readyState==4) { if (xmlhttp.status==200) { loadDefinitions(xmlhttp.responseXML); } } }

Using AJAX is a tradeoff. You gain greater control over a document and reduce the amount of information that must be passed from client to server. You also avoid the annoying flicker of page refreshes on pages that need to be frequently updated. Unfortunately, you also increase the complexity of the application and risk browser incompatibilities. Instead of simply printing text back at the request of a client browser you now have to script the interaction back and forth between the client and server. These drawbacks and not ignorance, as some articles have implied, have caused developers to shy away from AJAX. Developers want to maximize the number of people who can see their pages. But times have changed. The vast majority of web surfers now use browsers that support AJAX.

Here is a simple application(download source here) that you can see in action at the bottom of this page. It displays funny definitions from a dictionary document located on the Project Gutenberg site titled 1811 Dictionary of the Vulgar Tongue by Captain Grose. On the server we will have a PHP Application server connecting to a MySQL database to query for random definitions. In PHP we will convert the recordset to XML for consumption by the client. On the client we will query the server at a timed interval using XMLHTTP and use the XML DOM to update the page using XML DOM methods.

Remember the tradeoff I mentioned? To use AJAX in the most beneficial way, you should focus on efficiency. Not just replacing the part of the page you wish to replace, but also minimizing bandwidth. For instance, assume this page weighs in at a slim 10Kb. If you wanted to display updated definitions (or stock quotes) by refreshing the page that comes to 60Kb per minute, 3600Kb per hour and so on. Using AJAX we can query our server for just the definitions, that weigh in around 1KB. So, since you have been reading this article your bandwidth savings amount to:

Before you go off and jump into a bathtub full of saved bytes to celebrate, remember to be miserly with the XML being passed each time. Don't waste space with hugeElementNamesThatWasteSpace. Below is an example XML fragment to demonstrate the "definition" XML being used on this page. I saved space by having one letter element and attribute names and placing the data in the attributes of each element. For those wanderering off in a rant over this technique, the purpose of this XML is simply transporting data within an application, not between applications. If the information were for external consumption I too fall into the camp with folks demanding self-describing syntax.

<t> <r t="DRURY LANE AGUE" d="The venereal disorder."/> <r t="RUM BUNG" d="A full purse. CANT."/> <r t="CATTLE" d="Sad cattle: whores or gypsies. Black cattle, bugs. CANT."/> <r t="TAYLE" d="See TAIL."/> <r t="TO RECRUIT" d="To get a fresh supply of money."/> </t>

Also keep in mind that AJAX is much more powerful than simply a tool to build rotating banners. You can interact with the data to, for instance change the number of records returned ( ), the refresh rate( seconds) or the program. It can be a methodology to build rich web applications that are much more responsive than typical click and refresh programs.

For this article I have intentionally kept the server end of things simple. We could create a Web Service with a nice WSDL definition, but I'll save that for another article if anyone is interested.