O'Reilly logo

Adding Ajax by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Getting Ready to Make a Move to Ajax

Ajax brings a whole new level of feedback and flexibility to web applications. Gone, or at least pushed gently aside, are the days when web page forms produced a result only after being submitted to a server. Gone also are static web pages of frozen HTML (Hypertext Markup Language) that could be read, but were unresponsive to the page reader's actions. Nowadays, web page developers can provide, directly within the page, much of the same functionality that used to require a round trip to the server.

Using Ajax, page components can be collapsed or expanded as required, populated on demand, and feedback to the user can range from a color fade to a system of strategically placed messages. Every element of the page can be used to make web service requests, thus creating more responsive pages and less frustration for the users. The end result is a sharper, tighter application.

Ajax applications can also make use of a host of Ajax-enabled libraries and web services from companies such as Google, Amazon, Adobe, Microsoft, and Yahoo!, as well as independent libraries such as Prototype, Dojo, MochiKit, and jQuery. Existing web services can often be used as they are or easily modified to work with Ajax.

Ajax is unique in that it's a cutting edge concept that's based on rather mature technology. Even some of the more esoteric effects can be created comfortably and with confidence; developers can be secure in the knowledge that any particular effect should work in most, if not all, modern browsers.

Ajax development has some challenging aspects, but it really is an 80-20 technology: 80 percent of the people interested in the technology need only about 20 percent of the capability. Much of the discussion related to Ajax is based on explorations in how far the concept can be pushed. Because of this, it may feel as if you're working with an extremely complex framework. This can be intimidating when you're just starting to consider how you can use Ajax in your sites, but in general, using the Ajax group of technologies is relatively simple with few moving parts. You don't have to spend months reading all that's been written or trying all of the libraries in order to create efficient and interesting Ajax functionality if, and this is a big if, you start out small and work your way up to bigger effects.

This book assumes you're one of the luckier Ajax developers: you already have a web application or pages in place, and you're now looking to add some new effects. This puts you solidly on the progressive enhancement road, which automatically makes you a good Ajax developer.

The term progressive enhancement originated with Steven Champeon in a series of articles for Webmonkey and as part of an SXSW presentation (see the Wikipedia page at http://en.wikipedia.org/wiki/Progressive_enhancement for more history). It implies that you start with a site or application that is already clean, standardized, and accessible, and only then do you add special effects using application techniques such as Ajax. Other developers and designers such as Dave Shea and Jeremy Keith have expanded on this. The Wikipedia article on progressive enhancement lists the following guidelines:

  • All basic content should be accessible to all browsers.

  • All basic functionality should be accessible to all browsers.

  • Sparse, semantic markup organizes the content.

  • Enhanced layout is provided by externally linked CSS.

  • Enhanced behavior is provided by unobtrusive, externally linked JavaScript.

  • End user browser preferences are respected.

We can also use terms such as graceful degradation to refer to progressive enhancement. It all means the same thing—the pages and applications will work with any type of browser, mouse, or keyboard, regardless of the presence of a screen reader, and even if scripting is turned off.

I subscribe to the concept of progressive enhancement (or graceful degradation, or unobtrusive scripting, or whatever you want to call it), and the examples in this book are based on this premise. While it's true that you cannot reproduce all types of effects in a nonscript environment (such as those used in Google Maps, which demand Ajax), I believe that we shouldn't limit access to our core site content and functionality merely for the sake of adding eye candy.

As you begin to work with Ajax and consider which effects you want to use, it's important to remember that the simplest effects most often provide the greatest return for your time and effort. Most of us are not trying to recreate the desktop in the browser, or the browser in the desktop for that matter. We simply want to add to or enhance the basic functionality of our existing web pages and applications. We're the lucky ones, as half our job—providing the basic, non-Ajax functionality—is already finished. Now comes the fun part.


The term Ajax originated in an article by Jesse James Garrett titled "Ajax: A New Approach to Web Applications" (see the article at http://www.adaptivepath.com/publications/essays/archives/000385.php.

Is it Ajax or AJAX? Is it a single word or an acronym for Asynchronous JavaScript and XML? Garrett used AJAX as a handy nickname for the set of technologies discussed in this chapter. However, the concept has since expanded beyond the technology itself; it's a whole new way of looking at the web and pushing beyond the boundaries of a traditional browser page. It is now very common to use the term Ajax to refer to this overall capability.

For the sake of simplicity, following what has become more or less a de facto standard, this book uses Ajax.

The Technologies That Are Ajax

Ajax is not built on new technologies, but focuses instead on the refinement and maturing of existing tools and environments. When Jesse James Garrett originally defined Ajax, he listed the associated technologies as:

  • XHTML (Extensible HTML) and CSS (cascading stylesheets) for page layout and presentation

  • XML (Extensible Markup Language) and XSLT (Extensible Stylesheet Language Transformations) for data interchange

  • Document Object Model (DOM) for interactivity

  • A specialized object (XMLHttpRequest) for client-server interaction

  • JavaScript (or JScript) to act as glue

All of these technologies have been around in one form or another for years.

Though most of the emphasis of Ajax is on the web service request, the concept extends beyond simple data access within the page. It's a way of looking at a web page and using existing and new technologies to make it more interactive and responsive. This includes a new way of looking at JavaScript and more sophisticated JavaScript libraries, as well as a fresh new look at dynamic HTML techniques from the 1990s. It's thinking outside the web page box, whether you are using these technologies to create desktop applications, or, as in our case, to add usefulness, sparkle, and spontaneity to existing web pages.

A Natural Progression

Ajax is the result of a natural progression of client-side functionality. If Garrett hadn't boxed the concept into one name, chances are good that someone else would have; the web development environment was already heading toward a new explosive interest in the combined technologies.

In the earliest days of the Web, all of an application's functionality resided on the server. Netscape introduced client-side scripting with JavaScript, which allowed some client-side interactivity, but web pages remained static. Other browsers that followed, such as Microsoft's Internet Explorer (IE), had their own implementations of scripting, and eventually an effort arose to provide a minimum definition of scripting standards; the result was ECMAScript.

However, it wasn't until the W3C specification work with the DOM and CSS that pages became more dynamic and script could be used to modify, move, hide, create, or remove individual web page elements. At that time, dynamic web page effects were given the term dynamic HTML or DHTML—a concept that's now been subsumed into Ajax.

While advancements were being made in scripting and presentation, efforts were also underway to create a markup language that wasn't dependent on any specific vocabulary and could be extended without being overly complicated to implement. The result, XML, was released in 1998.

From this point, progress took multiple paths, and we entered an era of great expansion in functionality. This divergence naturally led to the advent of cross-browser incompatibilities, some of which still exist to this day. Among the browser-proprietary objects was one that would become the heart and soul of Ajax—Microsoft's IE 5 ActiveX object, Microsoft.XMLHTTP. Though it might have remained an IE-specific object, the concept caught the interest of other browser developers, and Mozilla created a variation called XMLHttpRequest.

XMLHttpRequest is special because it allows users to directly access asynchronous web services from within a web page. Rather than submitting data to the server through a form and then displaying the result in a separate page, XMLHttpRequest lets scripts invoke a server function and process the result without having to reload the page. The asynchronous aspect of the web service request means that the page isn't locked on hold while it waits for the service to respond.

Garrett also mentioned the use of XSLT, which can be partnered with XML to present the results of web service requests. However, a more popular approach is to use the DOM and new object notation such as JSON (JavaScript Object Notation) in addition to XML to manipulate existing page elements and manage the results of the web requests.

In summary, the development of web page functionality has led us from simple static web pages to all the functionality currently supported in Ajax today, with a few stops along the way:

  • Static web pages with HTML-managed presentation and formatting

  • Interactive functionality using JavaScript and variations such as JScript

  • Separation of presentation and markup through the use of CSS

  • Exposure of page elements to dynamic manipulation through the use of scripting

  • Extensible markup provided by XML

  • Web service requests and in-page XML processing

The Technologies: Book View

The JavaScript incorporated into the majority of Ajax applications in use when this book was written is based on the ECMAScript specification ECMA 262. It is more or less equivalent to the version of Microsoft's JScript found in IE 6.x and IE 7. It is also roughly equivalent to JavaScript 1.5 in Gecko-based browsers such as Firefox and Camino, and it is supported in Opera (9x), Safari 1.2, the Safari WebKit (development version for future versions of Safari), Konqueror, and other modern graphical browsers. This version of JavaScript is also supported in other user agents, for example personal assistants such as BlackBerry and iPhone.

Our next technology, the DOM, allows access to unique page elements and their attributes. The techniques and examples in this book are based on the Browser Object Model, or BOM (typically thought of as DOM Level 0), as well as DOM Levels 1 and 2. These are supported, with varying degrees of success and completeness, by the browsers mentioned above. As we examine Ajax, I'll note where the differences are.

Because this book focuses mainly on adding Ajax to existing sites and applications (from the client side), I will keep the discussion of server-side applications to a minimum. However, when required, PHP is the scripting language used to provide server-side functionality throughout this book. It is one of the simplest and most common server languages.

All of the examples in the book are XHTML-compliant, except where XHTML is not supported by the Ajax effect. For instance, Google Maps doesn't work in XHTML and the page is formatted as HTML 4.01 strict.

Additionally, all the examples are run in standard mode (rather than quirks mode) by providing a DOCTYPE for the page—either HTML 4.01 strict or XHTML 1.0 strict.


Quirks mode allows a browser to maintain backward compatibility with older browsers and stylesheets. For instance, IE uses an older CSS box model when no DOCTYPE is provided or when the DOCTYPE is not a standard variation.

Changing a file's extension to .xhtml and adding the DOCTYPE may not be enough to run some of the examples on particular browsers. For example, Internet Explorer doesn't support the application/xhtml+xml MIME type, and Firefox defaults to HTML. In an Apache environment, one trick to get XHTML documents to serve correctly in various agents is to make the following modifications to an .htaccess file:

AddType text/html .xhtml
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_ACCEPT} application/xhtml\+xml
RewriteCond %{HTTP_ACCEPT} !application/xhtml\+xml\s*;\s*q=0
RewriteCond %{REQUEST_URI} \.xhtml$
RewriteCond %{THE_REQUEST} HTTP/1\.1
RewriteRule .* - [T=application/xhtml+xml]

If the use of .htaccess is restricted or not supported by the web server, you can specify the MIME type in the applications that return the pages. For example, you can make the following PHP modification:

if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) {
  header("Content-type: application/xhtml+xml");
else {
  header("Content-type: text/html");

Another alternative in getting an example to work properly is to simply give it a .html extension. This works with all the book examples except for those using PHP and those using embedded Scalar Vector Graphics (SVG), which is covered in Chapter 8.

All of the examples make use of CSS Levels 1 and 2. In order to avoid the workarounds caused by browser oddities, the examples in this book deal with the CSS features supported by all the browsers.

To ensure the examples and HTML/XHTML markup are valid, they have been run through one of the following validators:

If you are using Firefox for development, all of these services can be accessed through the Web Developer Toolbar for Firefox or through the Total Validator Firefox extension. Though the examples work in all the target browsers (discussed later), for development purposes I recommend and assume you are using Firefox with Firebug installed as your primary development browser. This browser works in all target environments, and I've found no other tool as effective for development and debugging than Firebug. I'm so impressed with it that I consider it absolutely essential for Ajax development.


Download Firefox from http://www.mozilla.com/en-US/firefox/. Download Firebug from http://getfirebug.com/.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required