An Introduction To Ajax

by David Teare

Originally published on BEA Dev2Dev Asugust 2005


As J2EE developers, it seems we are constantly focused on "backend mechanics." Often, we forget that the main success of J2EE has been around the Web application; people love developing applications that utilize the Web for many reasons, but mainly because the ease of deployment allows a site to have millions of users with minimal cost. Unfortunately, over the years we have invested too much time in the back end and not enough time in making our Web user interfaces natural and responsive to our users.

This article introduces a methodology, Ajax, you can use to build more dynamic and responsive Web applications. The key lies in the combination of browser-side JavaScript, DHTML, and asynchronous communication with the server. This article also demonstrates just how easy it is to start using this approach, by leveraging an Ajax framework (DWR) to construct an application that communicates with backend services directly from the browser. If used properly, this tremendous power allows your application to be more natural and responsive to your users, thereby providing an improved browsing experience.

The sample code used in this application is available for download as a standalone WAR file.


The term Ajax is used to describe a set of technologies that allow browsers to provide users with a more natural browsing experience. Before Ajax, Web sites forced their users into the submit/wait/redisplay paradigm, where the users' actions were always synchronized with the server's "think time." Ajax provides the ability to communicate with the server asynchronously, thereby freeing the user experience from the request/response cycle. With Ajax, when a user clicks a button, you can use JavaScript and DHTML to immediately update the UI, and spawn an asynchronous request to the server to perform an update or query a database. When the request returns, you can then use JavaScript and CSS to update your UI accordingly without refreshing the entire page. Most importantly, users don't even know your code is communicating with the server: the Web site feels like it's instantly responding.

While the infrastructure needed by Ajax has been available for a while, it is only recently that the true power of asynchronous requests has been leveraged. The ability to have an extremely responsive Web site is exciting as it finally allows developers and designers to create "desktop-like" usability with the standard HTML/CSS/JavaScript stack.

Traditionally in J2EE, developers have been so focused on developing the service and persistence layers that the usability of the user interface has lagged behind. It is common to hear phases such as, "we don't have time to invest in the UI" or "you can't do that with HTML" during a typical J2EE development cycle. The following Web sites prove that these excuses don't hold water any longer:

All these Web sites show that Web applications don't need to rely solely on pages being reloaded from the server to present changes to the user. Everything seems to happen almost instantly. In short, when it comes to designing a responsive user interface, the bar has now been set much higher.

Defining Ajax

Jesse James Garrett at Adaptive Path defined Ajax as follows:

Ajax isn't a technology. It's really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

  1. Standards-based presentation using XHTML and CSS
  2. Dynamic display and interaction using the Document Object Model
  3. Asynchronous server communication using XMLHttpRequest
  4. JavaScript binding everything together

This is all fine and dandy, but why the name Ajax? Well, the term Ajax was coined by Jesse James Garrett, and as he puts it, it is "short-hand for Asynchronous JavaScript + XML."

How Does Ajax Work?

The kernel of Ajax is the XmlHttpRequest JavaScript object. This JavaScript object was originally introduced in Internet Explorer 5, and it is the enabling technology that allows asynchronous requests. In short, XmlHttpRequest lets you use JavaScript to make a request to the server and process the response without blocking the user.

By performing screen updates on the client, you have a great amount of flexibility when it comes to creating your Web site. Here are some ideas for what you can accomplish with Ajax:

  • Dynamically update the totals on your shopping cart without forcing the user to click Update and wait for the server to resend the entire page.
  • Increase site performance by reducing the amount of data downloaded from the server. For example, on Amazon's shopping cart page, when I update the quantity of an item in my basket, the entire page is reloaded, which forces 32K of data to be downloaded. If you use Ajax to calculate the new total, the server can respond with just the new total value, thereby reducing the required bandwidth 100 fold.
  • Eliminate page refreshes every time there is user input. For example, if the user clicks Next on a paginated list, Ajax allows you to just refresh the list with the server data, instead of redrawing the entire page.
  • Edit table data directly in place, without requiring the user to navigate to a new page to edit the data. With Ajax, when the user clicks Edit, you can redraw the static table into a table with editable contents. Once the user clicks Done, you can spawn an Ajax request to update the server, and redraw the table to have static, display-only data.

The possibilities are endless! Hopefully you are excited to get started developing your own Ajax-based site. Before we start, however, let's review an existing Web site that follows the old paradigm of submit/wait/redisplay and discuss how Ajax can improve the user's experience.

Example of Where Ajax Could Be Used: MSN Money

I was on the MSN Money page the other day, and it had an article about real estate investing I found intriguing. I decided to use the "Rate this article" feature of the site such that other users of the site might be encouraged to invest their time in reading the article. After I clicked the vote button and waited a second, the entire page refreshed and I was presented with a beautiful thank you where the original voting question was.

Figure 1
Figure 1. Thank you message

Ajax could have made the user experience more pleasant by providing a more responsive UI and eliminating the flicker of the page refresh. Currently, since the entire page is refreshed, a lot of data needs to be transmitted because the entire page must be resent. If you used Ajax, the server could have sent back a 500-byte message containing the thank you message instead of sending 26,813 bytes to refresh the entire page. Even when using high-speed Internet, the difference between transmitting 26K and 1/2 K is significant! Of equal importance, instead of redrawing the entire screen, only the small section regarding votes would need to be redrawn.

Let's implement our own rudimentary voting system that leverages Ajax.

Raw Ajax: Using the XmlHttpRequest Directly

Note: If you've already installed the ajax-demo.war in your local WebLogic container, you can navigate to http://localhost:7001/ajax-demo/raw-ajax.html.

Browse the application, cast some votes, and witness firsthand how it behaves. Once you're familiar with the application, continue reading to dig into the details of how it works.

First, you have some simple anchor tags that link to a JavaScript castVote(rank) function.

function castVote(rank) {

  var url = "/ajax-demo/static-article-ranking.html";

  var callback = processAjaxResponse;

  executeXhr(callback, url);


This function creates a URL for the server resource you want to communicate with, and calls your internal executeXhr function, providing a callback JavaScript function to be executed once the server response is available. Since I need this to run on a simple Apache setup, the "cast vote URL" is just a simple HTML page. In real life, the URL called would tally the votes and dynamically render a response with the vote totals.

The next step is the spawning of an XmlHttpRequest request:

function executeXhr(callback, url) {

  // branch for native XMLHttpRequest object

  if (window.XMLHttpRequest) {

    req = new XMLHttpRequest();

    req.onreadystatechange = callback;"GET", url, true);


  } // branch for IE/Windows ActiveX version

  else if (window.ActiveXObject) {

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

    if (req) {

      req.onreadystatechange = callback;"GET", url, true);





As you can see, executing a XmlHttpRequest is not trivial, but it is straightforward. As always in JavaScript land, the majority of the effort is spent ensuring browser compatibility. In this case, you first determine if the XmlHttpRequest object is available. If it is not, you are likely dealing with Internet Explorer, in which case you  use the ActiveX implementation provided.

The most relevant part of the executeXhr() method is these two lines:

req.onreadystatechange = callback;"GET", url, true);

The first line defines the JavaScript callback function you want to be automatically executed once the response is ready, and the "true" flag specified in the method means you want to execute this request asynchronously.

Once the XmlHttpRequest is processed by the server and returned to the browser, the callback method that you set using the req.onreadystatechange assignment will be automatically invoked:

function processAjaxResponse() {

  // only if req shows "loaded"

  if (req.readyState == 4) {

    // only if "OK"

    if (req.status == 200) {

      $('votes').innerHTML = req.responseText;

    } else {

      alert("There was a problem retrieving the XML data:\n" +





This code is quite terse and uses a few magic numbers, which makes it hard at first to understand what is happening. To clarify this, the following table (borrowed from details the common XmlHttpRequest object properties.

Property Description
onreadystatechange Event handler for an event that fires at every state change
readyState Object status integer:
  1. 0 = uninitialized
  2. 1 = loading
  3. 2 = loaded
  4. 3 = interactive
  5. 4 = complete
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
status Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusText String message accompanying the status code

Now the processVoteResponse() function makes a bit more sense. You first check the overall status of the XmlHttpRequest to ensure it is complete (readyStatus == 4), and then you interrogate the request status as set by the server. If everything is OK (status == 200), you proceed to rewrite the contents of the "votes" node of your DOM by using the innerHTML attribute.

Now that you see firsthand how the XmlHttpRequest object works, let's abstract away the gory details by leveraging a framework built to simplify asynchronous JavaScript communication with Java applications.

Ajax: DWR Style

Following along the same thread of the article rating system, we will implement the same functionality using the Direct Web Remoting (DWR) framework.

Assume that the articles and votes are stored in a database and that you will use some kind of object/relational mapping technique to extract them. To make it as easy as possible to deploy, no database will be used for persistent storage. Furthermore, to keep the application as generic as possible, no Web framework is used either. Instead, the application will start with a static HTML file, which you can assume is rendered dynamically by the server. Despite these simplifying assumptions, your application will use the Spring Framework to tie everything together, thereby making it easy to see how DWR can be leveraged in a "real" application.

Now would be a good time to download the sample application and familiarize yourself with it. The application is bundled as a standard WAR file so you should be able to simply drop it into any Web container—no configuration is needed. Once deployed, browse to http://localhost:7001/ajax_demo/dwr-ajax.html to run the application.

You should view the HTML source code to get an idea of how things work. The most interesting part is how simple the code is—all the interaction with the server is hidden behind the ajaxSampleSvc JavaScript object. What is even more amazing is that the ajaxSampleSvc service was not hand-coded; it was all automatically generated for us! Jump ahead to see how.

Pages: 1, 2

Next Page »