Tech 24 Mar 2005 05:05 pm

Playing with Ajax

Ajax is the fashionable expression of the month, it seems. It stands for “Asynchronous JavaScript + XML”, and it’s actually a mix of several well-known technologies that people have been using for a while: XHTML/CSS, DOM, XML/XSLT, Javascript and the XMLHttpRequest object.

So, it’s nothing new, but, thanks mostly to Google (and web applications such as Gmail, Google Suggest and Google Maps) it is now in fashion. Also, it has been only recently that browsers became standard-compliant enough that these technologies can be used with relatively consistent and reliable results across the most used versions: IE 6.0 and Firefox 1.0.x.

And I’ve decided to play with it for a while, mostly to get a feel of how it works and what can be done with it (and how easily). The first step, of course, was to find something I needed done that could benefit from Ajax. The one thing I came up with was a page I have where a small part of the content is generated by a CGI script: it shows the current time and temperature in a group of cities around the world, and the temperature data can take a while to be retrieved and displayed. The effect would be that the page would partially load, stop for several seconds while the data was retrieved from the CGI, and then finish loading.

The temperature info is not the most important info in the page, and it’s ok if it’s not displayed at all; but it’s nice to have. The original code looked like this:

<script source=”/cgi-bin/getweather.pl?long&js&mel”>

getweather.pl returns the city full name and the temperature as a document.write Javascript command (the “js” parameter requests a Javascript output). I replaced this with a placeholder to be filled later:

<div id=”mel”>Melbourne: __._°C</div>

This was done for each of the cities listed on the page, of course (with a different id for each; the id will be used to reference each entry later on and insert the temperature data). Then I modified the CGI script so that it became capable of returning data in a new format, XML. The return format looks like this:

<response>
<title>temperature</title>
<query>temperature</query>
<mel>Melbourne: 17.8&deg;C<br/></mel>
<syd>Sydney: 20.0&deg;C<br/></syd>
</response>

Note that it contains data for more than one city. With the data in this format, I can use Javascript methods to retrieve all the information I expect from the XML document and insert it in the right place in the HTML file being displayed.

Finally, I added to the end of the page the Javascript code that retrieves the data from the server and sprinkles it over the page that was already displayed to the user:

var req, city;
var myurl = “http://www.netwhatever.com/cgi-bin/getweather.pl?long&xml&mel&syd”;

function doRequest(url)
{
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = finishRequest;
        req.open(”GET”, url, true);
        req.send(null);
    } else if (window.ActiveXObject) {
        req = new ActiveXObject(”Microsoft.XMLHTTP”);
        if (req) {
            req.onreadystatechange = finishRequest;
            req.open(”GET”, url, true);
            req.send();
        }
    }
}

function finishRequest()
{
    if (req.readyState == 4) {
        if (req.status == 200) {
            response = req.responseXML.documentElement;
            syd = response.getElementsByTagName(’syd’)[0].firstChild.data;
            mel = response.getElementsByTagName(’mel’)[0].firstChild.data;
            document.getElementById(”syd”).innerHTML = syd;
            document.getElementById(”mel”).innerHTML = mel;
        }
    }
}

doRequest(myurl);

doRequest is the function that starts the asynchronous request (note that it needs to deal with differences between Firefox and IE). When the request finishes, finishRequest is called and, if everything went ok (return code 200), it parses the XML data and populates the DIVs created earlier on with the right data (it rewrites the innerHTML attribute of the DIVs). (technically, finishRequest is called for every change of the state in the request: state 4 means the request is finished; we ignore the other states and act only when it finishes)

So, not that complicated, and very powerful. This is a simple example that retrieves always the same information with no user interaction, but it can be easily extended to do much more interesting things (as Google has demonstrated). It “pushes the envelope” of what users may expect from online apps, really.

One Response to “Playing with Ajax”

  1. on 20 Jun 2005 at 9:38 pm 1.Mark said …

    Why not make the XML more generic? You could use <loc id=”syd”> rather than <syd>, then use getElementById(’syd’) rather than getElementByTagName(’syd’).

    That would also allow you to get all the cities as an array (getElementsByTagName(’loc’)), and you could fill the data programmatically rather than the current hard-coded method. Adding an extra city would then be less work.

Subscribe to the comments through RSS Feed

Leave a Reply