An Introduction To Ajax

Monday 24th of October 2016 10:39:53 AM by David Teare, 08/29/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:

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

As alluded to above, the heart of Ajax is the XmlHttpRequest JavaScript object. The following sample article ranking system was built to walk you though the low-level basics of Ajax: 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) {
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.

and unpredicable placement on the page. 

<IMG SRC="ugly2.gif">

If you resize the  browser window the image jumps around as the lines re-wrap.  Here's an in-line greyscale image with default settings and unpredictable placement on the page.  If you resize the browser window the image jumps around as the lines re-wrap.  In this case, the image is in the same directory as this

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() {
if (req.readyState == 4) {
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.

Introducing DWR

As demonstrated in the Raw Ajax section, using the XmlHttpRequest directly for creating asynchronous requests is cumbersome. Not only is it verbose in the JavaScript code, you must consider the server-side work needed to route your Ajax requests to the appropriate service, and marshal the result back to the browser.

DWR was invented to handle all the plumbing required to wire up your Web page to your backend services. It is a Java framework you can easily plug into your Web applications to allow your JavaScript code to call services on the server. It even integrates directly with the Spring Framework to allow you to expose your beans directly to the Web client.

What's really neat about DWR is that once you configure the services you want to expose to the client, it uses reflection to generate JavaScript objects that your Web page can use to access your service. Your Web page then simply interfaces with the generated JavaScript objects as if they were using the service directly; DWR seamlessly takes care of all of the dirty details of Ajax and request routing.

Let's dissect our example code to clarify how this works.

Application in Detail: DWR Dissected

The first thing to notice about the application is that it is a standard Java application using the Layered Architecture design pattern. The fact you will use DWR to expose some of your services via JavaScript doesn't affect your design.

Figure 2
Figure 2.

Here is a simple Java service that we will expose directly to our JavaScript code using the DWR framework:

package com.tearesolutions.service;
public interface AjaxSampleSvc {
Article castVote(int rank);

This is an incredibly simplified example, as you only have one Article that can be voted on. This service is managed by Spring under the bean name ajaxSampleSvc, and depends on the ArticleDao for its persistence needs. See applicationContext.xml for details.

To configure DWR to expose this service as a JavaScript object, you add the dwr.xml file to the WEB-INF directory:

<?xml version="1.0" encoding="UTF-8"?>
"-//GetAhead Limited//DTD Direct Web Remoting 0.4//EN"
<create creator="spring" javascript="ajaxSampleSvc">
<param name="beanName" value="ajaxSampleSvc" />
<convert converter="bean" match="com.tearesolutions.model.Article"/>
<exclude method="toString"/>
<exclude method="setArticleDao"/>
The dwr.xml file tells DWR what services you want to expose directly to your JavaScript code. Notice that you have asked to expose the ajaxSampleSvc Spring bean. DWR will automatically find the Spring ApplicationContext set up by your application. To do this, it requires you to use the standard ContextLoaderListener servlet filter to initialize your Spring ApplicationContext.

DWR is set up as a servlet, and so you add its definition to your web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN" "">
<display-name>Ajax Examples</display-name>
<display-name>DWR Servlet</display-name>
<description>Direct Web Remoter Servlet</description>

After this is complete, you can load http://localhost:7001/ajax-demo/dwr to see firsthand what services are available. Doing so shows the following:

Figure 3
Figure 3. The available services

Clicking the ajaxSampleSvc link takes you to a sample implementation of how you could use the service directly within your HTML page. Two included JavaScript files do the majority of the work:

<script type='text/javascript'
<script type='text/javascript'

The ajaxSampleSvc.js is generated dynamically:

function ajaxSampleSvc() { }
ajaxSampleSvc.castVote = function(callback, p0)
DWREngine._execute(callback, '/ajax-demo/dwr',
'ajaxSampleSvc', 'castVote', p0);

Now you can go back and refactor your raw-ajax.html file by replacing all the XmlHttpRequest code with this ajaxSampleSvc JavaScript object. The result of this change can be seen in the dwr-ajax.html file; following are the new JavaScript functions:

function castVote(rank) {
ajaxSampleSvc.castVote(processResponse, rank);
function processResponse(data) {
var voteText = "<h3>Thanks for Voting!</h3>"
+ "<p>Current ranking: " + data.voteAverage
+ " out of 5</p>"
+ "<p>Number of votes placed: "
+ data.numberOfVotes + "</p>";
$('votes').innerHTML = voteText;

Amazingly simple, isn't it? The Article domain object returned by the ajaxSampleSvc object is serialized into a JavaScript object, allowing you to call methods on it such as numberOfVotes() and voteAverage(). You use this data within the HTML code that you dynamically generate and insert into the "votes" DIV element.

Future Work

In a follow-up article, I will extend the conversation on Ajax to include these concepts:

  1. Ajax Best Practices

    Like many technologies, Ajax can be a double-edged sword. There are several use cases where Ajax is overkill for an application and actually hampers usability. I will review some anti-patterns to avoid, highlight some of the negative aspects of Ajax, and show mechanisms to help alleviate them. For example, was Ajax a suitable solution for the Netflix movie browser? Or, how do you cue the user that something really is happening, and clicking the button multiple times will not help?

  2. Managing State Across Requests

    When using Ajax, the document DOM is changed from the original and there's often a lot of page state information that gets stored in client-side variables. When users follow a link to another page in your application, that state is lost. When users inevitably click the Back button, they are presented with the original page from the cache. This can make for very confused users!

  3. Debugging Techniques

    Performing more work on the client side using JavaScript requires some debugging tools to help understand what's going on when things aren't going the way you want.


This article introduced Ajax, and showed how you can use it to create a dynamic and responsive Web application. By using the DWR framework, you can easily incorporate Ajax into your site without worrying about all the mundane plumbing work that must be performed.

Special thanks to Joe Walker and his team at the Getahead IT consultancy for making such a wonderful tool in DWR. Thank you for sharing it with the world!




italic | oblique | normal

The default value of none means about whatyou'd expect: no image is placed in the background. If you wanta background image, then you need only give this property aURL value:

BODY {background-image: url(bg23.gif);}

Due to the default values of otherbackground properties, this will cause the imagebg23.gif to be tiled in the document's <IMG SRC="shiny.gif" ALT="Shiny object"> </DIV>

As Figure 4-14 shows, this will center the image.

Figure 4-14

Figure 4-14. Centering images the hard way

For Western languages, which are read from left to right, the default value of text-align will be left, with text lining up on the left margin and having a ragged right margin (otherwise known as "left-to-right" text). Other languages, such as Hebrew andbeen displayed by the user agent. In this case, it's up to theuser agent to decide whether or not the document should be reflowed.The CSS specifications explicitly state that user agents are notrequired to reflow previous content to accommodate things whichhappen later in the document. In other words, if an image is floatedup into a previous paragraph, it may simply overwrite whatever wasalready there. On the other hand, the user agent may handle thesituation by flowing content around the float, even though doing soisn't required behavior. Either way, it's probably a badidea to count on a particular behavior, which makes the utility of

[ <length> | <percentage> ]{1,4}


Percentage values refer to the width of the parent element.

As you can see, this property accepts any length value or apercentage. That's all. So if you want all