An Introduction To Ajax

An Introduction To Ajax

by David Teare
08/29/2005

Abstract

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.

Introduction

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

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: http://tearesolutions.com/ajax-demo/raw-ajax.html. 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;
    req.open("GET", url, true);
    req.send(null);
  } // branch for IE/Windows ActiveX version
  else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = callback;
      req.open("GET", url, true);
      req.send();
    }
  }
}

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;
req.open("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 req.open() 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" +
      req.statusText);
    }
  }
} 

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 http://developer.apple.com/internet/webcontent/xmlhttpreq.html) details the common XmlHttpRequest object properties.

PropertyDescription
onreadystatechangeEvent handler for an event that fires at every state change
readyStateObject status integer:
  1. 0 = uninitialized
  2. 1 = loading
  3. 2 = loaded
  4. 3 = interactive
  5. 4 = complete
responseTextString version of data returned from server process
responseXMLDOM-compatible document object of data returned from server process
statusNumeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusTextString 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"?>
<!DOCTYPE dwr PUBLIC
 "-//GetAhead Limited//DTD Direct Web Remoting 0.4//EN"
 "http://www.getahead.ltd.uk/dwr/dwr.dtd">
	
<dwr>
 <allow>
  <create creator="spring" javascript="ajaxSampleSvc">
   <param name="beanName" value="ajaxSampleSvc" />
  </create>
  <convert converter="bean" match="com.tearesolutions.model.Article"/>
  <exclude method="toString"/>
  <exclude method="setArticleDao"/>
 </allow>
</dwr>

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" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
 <display-name>Ajax Examples</display-name>

 <listener>
  <listener-class>
      org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
	
 <servlet>
  <servlet-name>ajax_sample</servlet-name>
  <servlet-class>com.tearesolutions.web.AjaxSampleServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet>
  <servlet-name>dwr-invoker</servlet-name>
  <display-name>DWR Servlet</display-name>
  <description>Direct Web Remoter Servlet</description>
  <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
  <init-param>
   <param-name>debug</param-name>
   <param-value>true</param-value>
  </init-param>
 </servlet>

 <servlet-mapping>
  <servlet-name>ajax_sample</servlet-name>
  <url-pattern>/ajax_sample</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
  <servlet-name>dwr-invoker</servlet-name>
  <url-pattern>/dwr/*</url-pattern>
 </servlet-mapping>
</web-app>

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' 
   src='/ajax-demo/dwr/interface/ajaxSampleSvc.js'></script>
<script type='text/javascript' 
   src='/ajax-demo/dwr/engine.js'></script>

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.

Conclusion

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!

Download

The source code for the application demonstrated in this article is available for download: ajax-demo.war (1.52 MB)

References

David Teare is a graduate of The University of Western Ontario. He and his wife currently live in the Greater Toronto Area, where their company Teare Software Solutions is based

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值