What is AJAX?

"The Web is changing. The 30-year-old terminal-like technology it was originally is gradually giving way to new ways of doing things. The power of AJAX allows for rich user interaction without the trouble that has bugged traditional web applications."

This is the introduction to the script.aculo.us website, and regardless your opinion about the so-called AJAX programming technique, they are fundamentally right: the web is changing. AJAX is at least one way to do things in a different way, enhancing - although arguably, in some cases - users' browsing experience.

Application examples

What is AJAX then? Nothing too new, but not too old either. I'd define AJAX as the rebirth of Javascript, for example, it's not only Javascript we're talking about. The acronym stands for Asynchronous Javascript And XML and it already gives an idea of the fundamentals of the technology: something build on asynchronous server requests and responses. This may be clear to coders, but the best way to try explaining this to everyday internet users is showing some famous applications:

Gmail: The first example? The most famous? The most used? Perhaps. Google aimed to impress both end users and geeks with its free, long-awaited email service. What's so unusual in this webmail application?
  • An innovative and intuitive interface, more similar to a desktop application than a traditional webpage.
  • Rich formatting through an effective, easy-to-use editor.
  • Online spell checker.
  • Instant (one click) email tagging, labels, contact groups etc.
  • Email auto save.
Kiko: This is a very neat online calendar, free to use and customizable. Features include:
  • Multiple user/contacts/events administration.
  • Personalization of the right click menu (it overrides your browser's default behavior).
  • Drag and drop events across the calendar.
  • Easily switch through different calendar views without any page refresh.
Writely: An online word processor. Although it is not as advanced as its desktop cousins, this is a truly admirable effort to port a desktop application to the web. The service is free for now and it allows users to create, edit, share, and export text documents. Among its features there are:
  • High degree of document formatting - modify font size, style, colors, alignment, insert images and links etc.
  • Enhanced exporting options - it can create HTML documents, Word documents, zip files etc.
  • Online spell-checker.
  • Ability to easily share and publish your work.

This list can continue, as new "AJAX-powered" applications are created nearly every day.

AJAX provides the web developer the ability to create web applications that look and feel like applications that run on the desktop. It does this by solving the 'partial update' problem. AJAX makes it possible for a web application to request data from the server (usually in response to a button click or other javascript 'event') and change a part of the current page to reflect the result of the query. Prior to AJAX, if the web developer wanted to retrieve any information from the server, a full page update was required. This may mean a full page load when the user clicks a help icon, spell checks a document, or performs a drag and drop operation that changes data on the server. AJAX solves this problem and opens the door for a host of AJAX-powered web applications.
There were some unconventional solutions to this problem prior to AJAX. I have ignored them for the purpose of this article as they were hacky or relied on a feature in a particular browser

How does it work?

Ajax is fundamentally the union of various technologies - not something new by itself:

  • (X)HTML, CSS, etc., used as presentation layer and format the information retrieved by the server: nothing special here.
  • The XMLHttpRequest object, which allows data exchange between client and server "silently", in an asynchronous way, without the need of refreshing and reloading a whole web page.
  • The DOM Object Model (DOM), an Object-Oriented way to represent and access HTML or XML.
  • XML and XSLT used for data interchange and manipulation.

The magic is undoubtedly in the XMLHttpRequest object, originally invented by Microsoft as an ActiveX object and then made available as a standard JavaScript class by Mozilla-based browsers. At least something which seems to be compatible with most browsers then.

A necessary step in any JavaScript script using the XMLHttpRequest object would be something like:

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    http_request = new ActiveXObject("Microsoft.XMLHTTP");
}

In order to have an http_request object to use later on which is independent from the browser type.

Let's now examine an example of elementary Ajax application. The following code is broken into different parts and commented, the uncommented source and a demo is available on degraeve.com.

For this simple example, we need to create a simple server-side script which will be called by our Ajax application. The script can be in any language, this one is in Perl.

#!/usr/bin/perl -w
use CGI;

$query = new CGI;

$secretword = $query->param('w');
$remotehost = $query->remote_host;

print $query->header;
print "<p>The secret word is <b>$secretword</b> and your IP is <b>$remotehost</b>.</p>";

Basically, it creates a new CGI object named $query, used to access the parameter which will be passed by our submission form, "w", and get the user's IP address. The script will then print the page header and a phrase containing the word entered in our form and the user's IP address.

And here's the simple Ajax application:
<html>
<head>
<title>Simple Ajax Example</title>
<!-- Just the first HTML tags of the page, and the beginning of the script -->
<script language="Javascript">
    function xmlhttpPost(strURL) {
        var xmlHttpReq = false;
        var self = this;
        // Mozilla/Safari
        if (window.XMLHttpRequest) {
            self.xmlHttpReq = new XMLHttpRequest();
        }
        // IE
        else if (window.ActiveXObject) {
            self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }

        self.xmlHttpReq.open('POST', strURL, true);

        self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        <!-- with the method open we initialize the connection, specifying that we want to send a POST request to the page
            "strURL" and that the connection is asynchronous (true). The third parameter is actually true by default and could
            have been omitted in this case. As we want to use the POST method, we need to set the content-type header for
            our request, in this case "application/x-www-form-urlencoded". -->

        self.xmlHttpReq.onreadystatechange = function () {
            if (self.xmlHttpReq.readyState == 4) {
                updatepage(self.xmlHttpReq.responseText);
            }
        }
        self.xmlHttpReq.send(getquerystring());
    }

    function getquerystring() {
        var form = document.forms['f1'];
        var word = form.word.value;
        qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
        return qstr;
    }

    function updatepage(str) {
        document.getElementById("result").innerHTML = str;
    }

</script>
</head>

<body>
<form name="f1">
  <p>Word: <input name="word" type="text"  ></p>
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/cgi-bin/simple-ajax-example.cgi")'>
  <div id="result"></div>
</form>
</body>
</html>

That's it.

The first reaction after reading so far would probably be "Ajax is not easy at all", well, I never said it was. To create a simple application which just prints something on the screen we had to go through a lot of code, and we could have done something similar with much less hassle. This was just a trivial example, very different from those large scale applications available online.

There's good news though, there are plenty of frameworks and toolkits which makes life easier for developers interested in using this programming technique. There are in particular various libraries built upon the Prototype framework such as the already mentioned Script.aculo.us and Rico for examples, and various frameworks which integrate Ajax in some way in any server side language, like Ruby on Rails or CakePHP, for example.

Conclusion

Undoubtedly Ajax can be used to create really powerful and innovative applications, but it shouldn't be abused or mis-used. There are a few things to keep in mind, when developing an Ajax application:

  • It requires Javascript to be enable on the client browser, and the developer obviously can't control that
  • The application may not compatible with all browsers, in particular older browsers will definitely not be able to access it.
  • It can be too much of a surprise for the user who never used an Ajax application before: it may experience delays in responses, some basic functionalities like the "Back" button might not work as expected etc.

There are actually many more things to consider before even start planning to develop an application, and can basically be summarized as follows:

"Do not use Ajax in your web application unless you know what you're doing"

Luckily, there are a lot of articles and resources out there, waiting for you.

Notes and Resources

[1] Script.aculo.us AJAX toolkit: http://www.script.aculo.us

[2] Gmail - Google's online webmail: http://mail.google.com/mail

[3] Kiko - Online calendar: http://www.kiko.com/

[4] Writely - Online word processor: http://www.writely.com/

[5] A venture forth Blog - Top 10 Ajax applications: http://www.aventureforth.com/?p=13

[6] HTTP - Webopedia entry: http://www.webopedia.com/TERM/H/HTTP.html

[7] AJAX - Wikipedia Page: http://en.wikipedia.org/wiki/AJAX

[8] XMLHTTP Wikipedia Page: http://en.wikipedia.org/wiki/XMLHTTP

[9] Dom Object Model - Wikipedia Page: http://en.wikipedia.org/wiki/Document_Object_Model

[10] degraeve.com - Simple Ajax Example: http://www.degraeve.com/reference/simple-ajax-example.php

[11] Prototype Javascript Framework: http://prototype.conio.net/

[12] Rico open-source Javascript library: http://openrico.org/

[13] Ruby on Rails: http://www.rubyonrails.org

[14] CakePHP framework: http://www.cakephp.org

[15] Alex Bosworth's Weblog: Ajax Mistakes: http://sourcelabs.com/ajb/archives/2005/05/ajax_mistakes.html

[16] AjaxMatters.com: http://www.ajaxmatters.com/r/welcome