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.

Tip

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.

Tip

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:

<?php
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.

Tip

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

Start Clean

Adding Ajax to your site is an opportunity to do that page cleanup you’ve probably been wanting to do for a long time, but couldn’t find the time. Dynamic effects and the use of old and outdated HTML don’t go together well, particularly if you’re moving objects around, collapsing and expanding columns, or doing in-place editing or help.

In a weblog post at O’Reilly Radar, Nat Torkington wrote the following account of Mark Lucovsky’s attempt to implement the same bit of Ajax functionality into two very different web sites; one clean and the other with a large amount of “baggage” (http://radar.oreilly.com/archives/2006/08/the_value_of_web_standards.html:

While at OSCON, Mark Lucovsky of Google sent us a bit of HTML that’d embed a slender map search widget into our conferences web site. It’s an easy way for attendees to find restaurants, hotels, parks, bars, etc. near the conference venue. Great idea, and an elegant demo of the Ajax Search API that Mark’s been working on.

Mark’s next speaking gig was at the Search Engine Strategies (SES) conference, so naturally he reached for the find-me-stuff-around-the-conference example. However, he rapidly ran into the messy HTML that is the SES web site. Whereas it had been a matter of seconds to add the JavaScript into the O’Reilly web page, adding it to the SES page was an ordeal.

That’s a vindication of the large amount of hard work that [the] O’Reilly design team put into redesigning pages so they were XHTML and CSS. It’s also a vindication of the standards themselves: we sometimes lose track of the bigger picture when we’re fighting our way through a twisty maze of namespaces, all alike. The point of the standards is not just to ensure that browsers can display the pages. The standards also ensure the pages form a platform that can be built upon; a hacked-together platform leads to brittle and fragile extensions.

Ajax is heavily dependent on CSS and even more dependent on the DOM. In Ajax applications, we can access individual elements and move them about, create them, or remove them on the fly. Due to the dependency on DOM, we can’t just embed script in a page, throw a couple of ID attributes on elements, and expect our effects to work. Ajax is really dependent on the page being clean before we begin.

Before jumping in and tearing web pages apart in order to add Ajax effects, it’s a good idea to first run your pages against various validators provided by the W3C (and others) to find and fix the current problem areas. Validation can help you determine how much work your pages need and can help you plan accordingly. Even if you’re going to redesign the pages, you’ll find that it’s easier to convert from one design to another if you start with a clean design.

XHTML and HTML Validators

The granddaddy of all validators is the W3C’s Markup Validation Service. To use the validator, enter a URL or upload a web page and the service will list, in minute detail, all those components that aren’t valid (or are valid but not encouraged).

The Markup Validation Service supports a variety of doctypes, such as XHTML 1.0 Transitional, HTML 4.01 Strict, XHTML 1.1, and even custom doctypes. Normally a doctype is given in the document, using syntax such as the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

You can override the doctype in the validation service in order to see how the page does with stricter specifications. You can choose to display the source with line numbers (helpful in debugging), or you can specify verbose mode for more detailed output. Figure 1-1 shows the output of the validator, listing several errors.

The W3C’s Markup Validation Service tells you how clean your page’s markup is
Figure 1-1. The W3C’s Markup Validation Service tells you how clean your page’s markup is

Another validator is the Total Validator, created by Andy Halford. This validator can take longer than the W3C’s, but you have an option (in the Advanced form) of providing an email address to have the results sent to you. The reason Total Validator takes so long is because of its impressive array of options. In addition to validation errors, the site also finds bad or missing links and misspelled words (which can be both localized and customized)—a nice double-check on the site.

One of the options is to check the accessibility of the site, and you can choose from a list of levels, including U.S. Section 508, and the three W3C Web Accessibility Initiative (WAI) levels. Another option allows you to set the number of pages validated (up to 20) and the depth (as defined in the site map). You can also skip specified paths within the site’s navigation.

The tool also provides a screenshot based on your browser, operating system, and screen resolution. This is a very handy option if you don’t have access to a specific browser in a particular operating system.

Figure 1-2 displays the results of running the validator against the O’Reilly main web page, including a screenshot taken in Konqueror v3.4 in Linux.

Using the Total Validator’s many options to closely examine a web page
Figure 1-2. Using the Total Validator’s many options to closely examine a web page

CSS Validators

I use Firefox for most of my browsing, and it’s also my primary target browser for testing. The reason I use it more than other browsers is because of all the extensions, including those for web developers. Among these is the aforementioned Firebug, which is used extensively throughout this book. Web Developer Toolbar (https://addons.mozilla.org/firefox/60) is another.

Among the features of Web Developer is a drop-down list with various validations that can be run on whatever page you’re currently viewing. The HTML option uses the W3C Markup Validation Service, discussed in the previous section. There’s also an option to validate the page’s stylesheet using the W3C CSS Validator.

The CSS validator accepts the URL of a site or an uploaded file. If you want to try out the CSS before you put it into a stylesheet and you’re not sure whether the syntax is valid, you can simply type in the CSS and have it checked. This option is handy—I tried it with the following code, which is from a stylesheet on one of my sites:

.comment-number {
       text-align: right;
       display: inline;
       font-size: 48pt;
       opacity: .3;
       filter: alpha(opacity=30);
       z-index: 3;
       padding-bottom: 0px; margin-bottom: 0px;
}

The result is shown in Figure 1-3. As you can see, the validator rejects the use of the nonstandard opacity settings.

Testing a block of CSS with W3C CSS Validator to see how well it meets the standard
Figure 1-3. Testing a block of CSS with W3C CSS Validator to see how well it meets the standard

Checking Accessibility

Why is accessibility so important? I’ve heard the argument that only five percent of page readers are impacted by page functionality that may fail these accessibility guidelines. However, ethical considerations aside, accessibility is becoming mandated more and more by law—many countries now mandate that all government pages meet accessibility guidelines. Accessibility is also becoming an important consideration for commercial sites. In fact, there’s currently a case pending against Target (a large chain of stores in the U.S. and elsewhere), where the company was successfully sued for not providing an accessible online web store (the case is under appeal). I expect this to be a continuing trend.

Tip

An excellent one-page listing of the best articles on accessibility and Ajax can be found at the Stanford Online Accessibility program at http://soap.stanford.edu/show.php?contentid=65.

Unlike validating CSS or XHTML, determining whether a page meets an accessibility guideline is as much inspection and personal interpretation as it is automated test results. The results from running an accessibility test at the Cynthia Says site can be quite extensive, and you’ll probably need to read the guidelines associated with the test. One of the most critical factors in using this site is choosing which standard you’re running the test against: one of the three W3C WAI 1.0 guidelines—Priority 1, 2, or 3—or the U.S. Section 508 guidelines.

Tip

Read more on the W3C WAI 1.0 guidelines at http://www.w3.org/TR/WCAG10/, and Section 508 at http://www.access-board.gov/sec508/standards.htm(Subpart_b).

The Total Validator also performs accessibility checks, again providing options for you to choose WAI or Section 508. Even with these tests, though, you’ll need to manually check your effort against the guidelines when finished. Something like a meaningful alt attribute description for an image element (which will help readers who can’t interpret images to know what’s missing) can’t be deduced from automatic testing.

Converting Tables to CSS Layouts

Page layout problems that trigger an error message are easy to identify. However, some page changes that are required to make a site optimal for Ajax development (and all other uses) don’t result in validation errors or accessibility warnings. One of the most common old layout tricks before the advent of CSS was using HTML tables to manage the page contents, regardless of content type. However, HTML tables were meant for tabular data, such as a listing of records from a database. For our purposes, HTML tables are not very adaptable to many Ajax effects. As I’ll demonstrate later in this chapter, and also in Chapter 6, updating a dynamic table is trickier than updating a discrete div element. In addition, you can’t necessarily move a table row or handle a table cell as a distinct object. HTML tables also drive the semantic web people batty—if you use HTML tables to present all of the information on a web page, the tabular data will not stand out.

Here are some of the issues with using HTML tables for all of your page content:

  • HTML table elements were created specifically for tabular data.

  • HTML tables add an extra layer of complexity when using JavaScript.

  • HTML table elements, such as rows and cells, exist within a framework that makes it awkward to work with an element individually.

  • HTML table elements can’t be easily collapsed, moved, or removed from the display without adversely effecting other elements.

  • Some JavaScript-based effects, such as layering, opacity, and other subtle effects can have a negative impact when used with an HTML table.

Based on all this, one of the most common Ajax preparation tasks is converting HTML tables to valid XHTML elements and CSS. Converting the page to CSS is going to make creating Ajax effects easier, and it is going to make site maintenance easier, too. Contrary to expectation, the conversion is actually not as hard as you may think. The next couple of sections explore how to do this, along with a few other conversion efforts. If your web site is already valid and making use of CSS and XHTML, you may want to skip these sections.

Tip

HTML tables were designed to display related data, such as a list of stores and locations or the results of a survey. Using them for general page layout is not semantically correct. You’ll hear mention of the semantics of an approach throughout the book. What this means (no pun intended) is that the elements used in the page are used in ways that are appropriate for their defined usage, not just for formatting. This can help screen readers and other devices to process the page more accurately. It can also help web bots, automated web robots used by search engines and other sites, process the data more efficiently.

Here’s a typical web page design: the header and footer extend the width of the page or the content, and the body of the page is broken into two vertical components, one as a sidebar and the other as main content. The sidebar can be on the left or right, and the page can be sized and centered or extended to the width of the browser window.

Using an HTML table in this case is simple: create one table with two columns and three rows, and use colspan to expand the column in the first and third rows to the width of the table. There are several different methods you can use to recreate this effect using XHTML and CSS. One is to create three blocks using div elements, each expanded to 100 percent of the container space, stacked one after the other, as shown in Figure 1-4.

Page converted to XHTML and CSS using div elements and the CSS float property
Figure 1-4. Page converted to XHTML and CSS using div elements and the CSS float property

To create the two columns in the middle space, add two div elements side by side instead of stacked, and sized so that the content column is wider. List the content column first in the actual page markup so that it will be the first one read by text-to-screen readers.

Normally div elements are block-level elements, which means they stack vertically. To align the columns side-by-side, use the CSS float property to float the block to the left or right, effectively removing the item from the vertical page flow. If the sidebar is going on the left, set its float value to left and set the content column’s float value to right. Example 1-1 shows the complete page.

Example 1-1. XHTML page with converted two-column page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Table Conversion</title>
<style type="text/css">
body { margin: 0; padding: 0 }
#wrapper { width: 800px; margin: 0 auto; }
#header { height: 100px; background-color: #00f; }
#sidebar {  width: 200px; background-color: #f00; float: left; }
#content {  width: 590px; background-color: #ff0;  padding: 5px; float: right; }
#footer { clear: both; background-color: #0f0; height: 50px; }
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
</div>

<div id="content">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in
vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis
at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum
zzril delenit augue duis dolore te feugait nulla facilisi.
</p><p>
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper
suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum
iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum
dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim
qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla
 facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat
volutpat. </p>
</div>
<div id="sidebar">
   <ul>
     <li>Option 1</li>
     <li>Option 2</li>
   </ul>
</div>
<div id="footer">
</div>
</div>
</body>
</html>

To remove the float property from the footer (so that it will appear below, rather than beside, the sidebar and content pages) the CSS clear property is set to both.

Viewing the page in Figure 1-4, notice that the left column, which is the sidebar, doesn’t extend all the way down if the content isn’t long enough. This is the drawback of using CSS-positioned XHTML: the column background extends only the length of the content.

One way of working around this problem is to set the same background color for all of the containers—this will hide the column length differences.

Another approach (and the one I prefer) is to create an image that is the same width and color of the sidebar, and then use it as a background image for the sidebar container. To use this method, set the background repeat attributes so that the image does not repeat horizontally or vertically, and position it where the sidebar would start. You can also set the background color of the container to be the same as the content column—this will fill in any area not covered by the background image. With this modification, both columns appear to be the same length. The modified style setting is:

#wrapper {
                  background-image: url(ajaxbackground.jpg);
                  background-position: top left;
                  background-repeat: repeat-y;
                  background-color: #ff0;
                  width: 800px;
                  margin: 0 auto;
                  }

The page with the modified container style setting is shown in Figure 1-5.

Modified container style settings make both columns appear to be the same length
Figure 1-5. Modified container style settings make both columns appear to be the same length

This is just one approach. There are many CSS-based layout possibilities. The one just described is a fixed layout. In a fluid layout, the column sizes change to fit the page size, and in an elastic layout, the column sizes are based on page size, but are not to exceed a maximum width. For additional reading on CSS layouts, search the Web for “fluid fixed elastic CSS layout.”

It can be difficult to get sites switched over from HTML tables to CSS because the tables are so handy and simple to use, and CSS can be a little daunting. Furthermore, a page will validate as XHTML regardless of whether it uses HTML tables. However, some web page elements simply will not validate and must be converted. In the next section, we’ll look at the most common of these elements.

Continuing the Conversion: Element by Element

Converting a page to XHTML and CSS is one major change, but there are a host of smaller, easier changes to make before the page validates as XHTML. These changes will make the page elements accessible for script access, which I’ll be demonstrating throughout this book.

Tip

There are a number of tools that can assist you in cleaning up your web pages and converting them from HTML to XHTML. A popular tool used for this purpose is HTML Tidy, available at http://tidy.sourceforge.net/.

In the early days of the browser, one of the first items people wanted to control was the font. If the entire page were black and white, with font family and size based only on the type of element, our sites would have been too uniform and far too dull (though it would have been easy from a designer’s perspective, not to mention fully accessible).

To provide for page customization, a few new HTML elements were introduced as the language developed, including one of the most notorious of all bad elements: blink. This element caused objects (text, images, etc.) to blink on and off. It has become universally hated and is a poster child for separation of page markup and presentation. Luckily, people only toyed briefly with blink, but another element that was widely used (and is still used) is font.

The font element gives designers the ability to specify a font family, size, and color:

<font size="4" color="blue" face="arial">
Some text
</font>

The font element lets us make our text more distinctive, but it does have a drawback: if we want to make a change to the font in our web content, we have to hunt down the use of font in all of our web pages and make the change manually. This can make page maintenance excruciating.

With the advent of CSS, the push is on to remove the use of font (and it has disappeared, more or less, from most pages). If the font element is present in your web sites or applications, you’d be wise to remove it and use a stylesheet setting instead. The following is the CSS setting for the font of a specific element:

#test { font-family: arial; font-size: 4em; color: #0000ff }

Other position- and style-specific elements have been deprecated or conflict with the use of Ajax and should be removed. Among these are:

center

This element is used to center objects. Use CSS to achieve this effect instead.

menu

This element is used to create menu lists. This effect should be replaced using unordered lists (UL).

Strike

This element creates strikethrough text (use CSS or DEL).

dir

This element is used to create a directory list and should be replaced using UL.

Applet

This element was used to include Java applets, but you should use object now.

The best way to determine whether a page contains deprecated elements is to set the DOCTYPE to the specification you want to support and then run the page through the validator. You will be notified by the validator if there are any unsupported elements.

Another aspect of HTML that is not compatible with XHTML is the use of tag closure with elements that may or may not have a terminating end tag. For instance, the img element has no end tag, as all the information about an image is included in the element tag. In XHTML, this tag should be closed with a forward slash just before the closing bracket:

<img src="some.jpg" alt="alternative text" />

When adding Ajax, it’s especially important that elements in a web page are properly closed; otherwise, you may get unexpected side effects when you begin to add dynamic effects. Among the more commonly unclosed elements are paragraphs (p) and list items (li). Closing them may seem like a minor headache, but it’s one that may prevent much larger headaches later on.

So, what happens once you’ve eliminated the obvious problems? Will all web browsers look and act the same? Oh, we can only wish.

Dealing with Browser-Specific Quirks

It may seem like every HTML element has predefined style settings. Headers are block-level elements, larger than paragraph text, increasing in size from h6 to h1. Each HTML list item has a default padding value. Paragraphs are block elements with specific margins and padding, fonts, and line spacing.

At first glance, these defaults appear to be relatively the same across browsers, but even minor variations can have significant impact on page design and Ajax effects. Browsers provide their own internal stylesheets that define these values, and though there are some constraints on the styling (such as paragraphs being block-level elements), other settings are based on the browser developers’ interpretation of W3C-specified guidelines.

Due to these variations, the amount of spacing between letters, sizes, and so on can differ. Link colors, list icons, and relative header sizes can also differ—significantly at times. This can cause a lot of problems in the page design and can produce unexpected side effects when adding Ajax.

Controlling the Page and Adding Ajax

Many effects in Ajax, such as just-in-time (JIT) help (in-page messages that are hidden until needed), placement, color fades, collapsible elements, and so on can only work effectively across browsers when the browsers’ various quirks are eliminated.

For example, Safari supports a different line height than Firefox—a quirk that doesn’t impact pages containing a great deal of text, but one that can create major problems for an Ajax application that positions text in a small box for a help system. If the text ends up being too large for some browsers and too small for others, the overall system is going to look amateurish or may be hard to read.

One of the worst offenders for invalid CSS has been IE, and some of the workaround hacks have actually been given names, such as Peekaboo Bug, Border Chaos, and the Guillotine Bug; entertaining names, but they’re a pain to work with.

Tip

Microsoft has made an effort in IE 7 to fix most of the browser’s CSS problems; for more information see http://blogs.msdn.com/ie/archive/2006/08/22/712830.aspx. Unfortunately, the browser isn’t perfect and still has quirks.

IE isn’t the only browser that has quirks, though—there is no gold standard. Each browser has its own personality. Unfortunately, personality isn’t necessarily a positive attribute in the browser marketplace. Perhaps if it were easy, it wouldn’t be as much fun.

If the font sizes, margins, and padding differ between browsers, even by minor amounts, elements serving as containers for dynamic text, such as list items or box elements, may be too small for the text, and the result will be wrapping or truncation. You’ll have far fewer of these problems if you use XHTML and comprehensive CSS stylesheets.

Taking Control

One approach to resolving cross-browser stylesheet differences is to create a custom stylesheet that optimizes each of the elements for a single browser, then add the necessary tweaks to make it look the same for the second browser (trying not to break the first), and then move on to the third, and so on. This can be a major job, especially for a site that’s using sophisticated styling and relatively complex Ajax.

Another approach is to remove all style settings from the stylesheet and add in only the ones that are needed. This can be a drastic change, but it will provide you with absolute control over the page layout, thereby ensuring that Ajax effects work as expected.

If you want to change style settings for all of your web elements, you can apply global settings—it’s as simple as typing the asterisk (*) character. The following code sets the margin and padding to 0, and sets the font (font-family) to Arial for all elements:

* { padding: 0; margin: 0; font-family: Arial }

It’s a simple style setting, but when applied to a page, the effects are dramatic.

Of course, removing or adjusting the settings for all elements means that you have to go through and define a style setting for every element, which can get tedious. A better approach might be to adjust the settings for just those elements that tend to give you the most problems across browsers, and leave the others at the default values. You can then package these defaults into a stylesheet that will be included in all pages just before a second stylesheet that contains each page’s unique settings.

One such global change you might consider is removing the underline from all hypertext links. The underline can mess up the page’s look and prove distracting, especially when you have a group of items that are all underlined. Underlines can also cut off the lower part of the letters with some fonts, making the words hard to read. The following setting will remove the underline from all links:

a { text-decoration: none}

The underline can then be added back in (again using CSS) for links within specified elements, such as an element containing a great deal of text and few links. Of course, one of the problems with using this approach is that the hypertext links aren’t as apparent on the page. What I do with my sites is use a font that’s compatible with link underlines and keep the underlines in my main content text. In sidebars and menus, the context should be enough to highlight that the text is wrapped in a link. Since the font can be smaller, or many linked items listed one after another, I remove the underline for a cleaner, easier-to-read page.

Another major cleanup task is setting headers to use the same size, padding, and margin using syntax similar to the following:

h1, h2, h3, h4, h5, h6{ font-size:  1em; padding: 0; margin: 0 }

These are really semantic elements, providing information for search engine bots and screen readers about the outline in the page:

h1 header one
   h2 header two
      h3 header three
      h3 header three
   h2 header two

We’ve gotten into the habit of using these header elements for boldness and size, which is completely contrary to their purpose. By removing these elements, we’re forced to use headers appropriately and use font styling where appropriate to create a visual effect. If you provide a graphical header, provide an h1 header for the content. If you don’t want it showing, turn off its visibility, but don’t remove it; it’s necessary for search engine optimization. A good compromise is wrapping the image in an h1 element, with the exact text in the alt attribute.

Once you’ve removed the most obvious errors, continue creating your own default stylesheet, removing or normalizing any element that proves itself problematic across browsers.

Tip

Threr is an interesting article by Tantek Çelik about creating a default scaffolding stylesheet at http://tantek.com/log/2004/09.html#d06t2354. A follow-up by Eric Meyer is located at http://meyerweb.com/eric/thoughts/2004/09/15/emreallyem-undoing-htmlcss.

After validating and cleaning up existing sites and applications, the next step in the process of adding Ajax is defining a plan for the type of changes you want to make to your site, including which frameworks to use and which target browsers and other user agents you need to support. To do all of this, you need to have a good understanding of your client base: your web page readers and your web application users.

Understanding Your Client Base

The amount of Ajax functionality that you introduce to your site depends on more than just how much you’re willing to add and maintain. Even the niftiest technology is going to fall flat if it doesn’t provide an added value, or worse, locks your users out of the site. What you will discover, though, is that if you listen to the feedback from your client base, you’ll be able to use a little scripting and a few in-page web services to really increase the usability of your site.

Discovering Your Clients

The first step in your Ajax makeover is discovering all you can about the people who visit your site so that you plan accordingly. Your best friends in this regard are your site’s logs. The following log entry is from one of my sites, and it is a fairly typical example:

5x.x2.x8.xx0 - - [31/Aug/2006:03:09:27 +0000] "GET /wp-content/themes/
bbgun/bbgung.png HTTP/1.1" 200 90338 "http://burningbird.net/wp-content/themes/bbgun/
style.css" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6)
Gecko/20060728 Firefox/1.5.0.6"

This log displays the date, the resource accessed, and a string containing information about the client’s operating system and browser. In this case, the browser is Firefox version 1.5.0.6, and the operating system is Windows. Another line from the log is:

x0.xx3.1xx.xx4 - - [31/Aug/2006:03:14:48 +0000] "GET /wp-content/themes/
words/eyesafe.png HTTP/1.1" 404 9058 "http://burningbird.net/" "Mozilla/5.0
(Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1b1) Gecko/20060707 Firefox/2.0b1"

This client is using Firefox 2.0, the first beta release, and the operating system is Mac OS X.

This information will help you determine which user agents (browsers and mobile devices) to support, and will allow you to compensate for the image, image resolution, font support, and tool support differences that exist between operating systems.

You can look at a logfile directly or you can use one of a variety of web tools such as AWStats or Webalizer to analyze the log. You can find these and others just by searching for “logfile analyzer” with your favorite search engine.

Other resources you can use to explore web access are the sites that track browser statistics, such as the W3 Schools at http://www.w3schools.com/browsers/browsers_stats.asp or The Counter at http://www.thecounter.com/stats.

To determine how many users have JavaScript enabled, add a NOSCRIPT section that loads a unique image, one that doesn’t impact on the page, and then check the logs to see how often the image has been accessed. With recent high-profile script-based security violations at Google and elsewhere, you’ll find that more people are disabling script as a security measure. Others may be using tools such as NoScript (http://noscript.net), a Firefox extension that allows you to enable JavaScript on a site-by-site basis. When designing your web content, expect that people will have script turned off, and unless the application is completely based on scripting, don’t put up notices about how people should turn scripting on for a better experience; this has become the equivalent of an Ajax blink.

An Open-Door Policy

I once asked readers at one of my sites which specific uses of Ajax they’d like to see on the site. One of the options I listed was a drop-down menu that popped open either when the mouse was over a top-level menu item or when the item was clicked—a quite common use of DHTML frequently extended to Ajax.

Surprisingly, the behavior of the drop-down menu wasn’t especially interesting to my readers. They tended to be more interested in having control over their interaction with the site than they were controlling the navigation between pages.

Now, if I had a more complex site structure, the menu might have been more essential. However, the difference between what I thought would be important to the page readers and what they actually reported demonstrates that you can’t assume what your page readers will want. Before you begin the process of adding Ajax to your site, it’s a good idea to get your readers involved—ask what they want to see, or test new technology in specific places and solicit feedback. Don’t be surprised, though, if you have to change both your assumptions and your implementation plan.

What if my page readers had wanted the DHTML drop-down menu? If my site structure had been more than two levels deep, I would agree, but I wouldn’t just implement the menu and then walk away. Dynamically generated navigation makes your site inaccessible for those who have turned off JavaScript, have difficulties using a mouse, or are using a text-to-speech browser.

Even if you find that 95 percent of your readers turn on script, use a mouse, or use a browser like Firefox, making your site inaccessible punishes those people who may already have enough challenges in their lives. Consider also that the most popular extension for Firefox is one that turns scripting off for sites by default (NoScript). You shouldn’t make any assumptions about how many people are using JavaScript, either. Finally, search engine web bots, such as Google’s and Yahoo!’s, can’t follow script-generated links, and therefore won’t pick up the material accessible only through the menu.

Some features may require JavaScript or the mouse. These might include online word processors, spreadsheets, or games, but should never include critical features such as the ability to navigate to main content pages and application documentation. Use the following recommendations when you are determining how to best incorporate your page readers’ needs:

  • Forget the surprise rollout; ask your page readers what they’d like to see before you begin.

  • Consider beta testing a change in one portion of your site and soliciting feedback before rolling it out across the site.

  • Balance requests against the amount of work required; the more moving parts the more things can break, and no reader likes a broken page.

  • Listen to people. If you roll out a change and it doesn’t work, be prepared and ready to pull it back and try something else.

The Plan

Now that you have a better idea of your page readers’ environments and preferences, it’s time to develop a plan for adding Ajax to your site. The difference between adding Ajax to a small site versus a big one is in the number of hours it will take, not in the steps you take.

The object that you change first is dependent on your reasons for adding Ajax. For instance, if you have an extensive customer application with lots of form pages, this would be an ideal place for adding Ajax; it’s an isolated application that could have big returns in terms of satisfaction, quality of response, and resource use once it’s Ajax-enabled. Ajax can also improve the overall performance of the application, making it even more of a win-win situation.

Other target areas are any pages where your readers have the ability to update or modify information. Adding Ajax to make the changes in-place can add enormously to the client’s satisfaction, while still being completely accessible.

Providing JIT help or feedback is an excellent use of Ajax. Just make sure that the same information is available if scripting is disabled or if clients are using a text-to-speech browser.

The addition of visual elements should not be your highest priority, but it’s a legitimate use of Ajax. These changes can add a nice “Wow” factor with minimum disruption of the site’s primary functionality.

Ajax should be added gradually, and you should back the site up before you add even one line of code. If you do need to add something globally, like a new Ajax-enabled menu that will appear on all of your site’s pages, encapsulate the code into a file that can then be incorporated into all your pages—such as a header file that’s incorporated into each page using server-side functionality.

Minimize the amount of code you’ll add to each page by organizing code into libraries and including only the desired library on each page. Or consider using one of the freely available Ajax libraries. Several Ajax libraries are covered in Chapter 3 and are used throughout this book.

When creating your plan, consider the following:

  • This is a nag, but can never be said too much: back up your site before you start and when each addition is published.

  • Determine your starting point; an isolated application makes a good candidate.

  • Examine areas where your site or application is already interactive and explore how Ajax can be used for improvement.

  • Make liberal use of JIT help and feedback, providing alternatives for clients who have scripting disabled.

  • Visual effects to enhance or accompany existing functionality add sparkle and effect, usually at minimum cost.

  • Look for opportunities to encapsulate reusable chunks of code, such as menu functions or online help.

  • Use existing libraries.

Designing a Framework for Your Site

The most important decision facing you now is whether to add Ajax to existing pages or to start from scratch. This book is based on an assumption that web developers begin by introducing Ajax into existing pages and applications rather than scrapping a site and starting anew. In other words, the client-side functionality is adapted, and the server-side component of the site is left as-is, more or less.

The next step in the decision process is to determine the extent of the Ajax modifications. If you’re changing a static web page form to one that uses script and XMLHttpRequest to support in-page edits, your use of the new technologies is relatively isolated and will have little impact on the overall site application.

However, if you’re adding a site-wide help system, a new dynamic menu, or an in-place search feature, all of your pages will be impacted, and you might want to consider some additional architecture changes, such as splitting out your header and all the script into separate files that can be included in all of your pages. This approach allows you to make sure all of the appropriate JavaScript libraries are included, and allows you to isolate objects like event handlers.

Many of the new content management systems are based on a modular approach that allows you to reuse the sidebar, headers, and footers as much as possible. If your site doesn’t use a modular system and the pages are managed manually, you might want to add this to your to-do list for future designs.

Tip

Whether you modularize your web pages or not, all of your custom JavaScript should be created in separate files that are included into the appropriate pages. When you change in the code in a script, it will automatically be propagated out to all the pages using that script.

Meet Your Reader

Earlier, I covered the importance of discovering your web page readers’ environments, including their browsers and operating systems, and determining whether they have JavaScript enabled. You’ll also need to work through an accessibility plan, including criteria used to judge each web page as it’s converted to Ajax. This will help to ensure the plan’s requirements are met.

I remember reading somewhere once that you only have to meet the needs of 90 or 95 percent of your web page readers. That may be true of people using older browsers, such as IE 5.5 for the Mac, but it isn’t true for people who face enough challenges in life without having more thrust on them just to access your site. This may include:

  • The visually impaired, who may use a text-to-speech browser

  • Those physically incapable of using a mouse

  • People who suffer from color blindness

  • The hearing impaired, who may not be able to listen to a podcast or hear auditory instructions

  • People with attention-deficit disorder or other learning-comprehension challenges, who may not be able to quickly comprehend fast-moving text or flashed messages

  • The tired, time-challenged, distracted, and stressed

In other words, all of us. Your readers may have a hard time reading font that’s tiny enough to require a magnifying lens to view. Adding in-page editing or dynamic search functionality doesn’t amount to much if you have to cram the additions into a space too small to be readable. Additionally, there are few things more irritating than having to wave the mouse around the page like a magic wand in order to discover where the site’s navigation objects are or which elements can be clicked to get access to critical information.

Safe and Secure

A site’s readers are also dependent on the developers providing a usable and safe environment. Part of a web site’s architecture is the inclusion of test procedures that check to make sure the page is still accessible in all of the target browsers and environments each time a change is added. Included in your upgrade plan should be procedures to stress test the changes.

You should also run tests to make sure the code isn’t taking more than its share of space on a reader’s computer. Most JavaScript applications use client-side storage for one reason or another and for the most part JavaScript cookies are sufficient for an application’s needs. However, several Ajax libraries have provided facilities to store additional data on the client’s computer using Flash or some other external storage. When developing your plan, investigate how much data must be stored on the client compared to the server. Client-side storage is an inherent security risk in any web application, Ajax-based or not.

You will also have to include security issues in your plan. As we progress through the book, I’ll point out areas of vulnerability with the different Ajax effects we explore. Still, the more moving parts your pages have, the more important it is to monitor sites that issue security releases and test your pages when browsers release updates.

Tip

Since this is a general-purpose book on adding Ajax, I can’t provide complete details on security issues. Instead, I recommend Christopher Wells’ book, Securing Ajax Applications (O’Reilly), which provides detailed coverage of Ajax and security.

Tight Coupling and Loose Coupling

As part of the framework for adding Ajax, web developers also need to decide on how tightly coupled client and server applications are.

A tightly coupled application is one in which most of the client side of the application is generated by or dependent on the server. In other words, there’s no way to really separate the two or the whole thing breaks.

A loosely coupled application, on the other hand, is one in which the web services could be called by an Ajax application, but could likewise be called by another web service. In addition, the client side of the application interfaces only with the API (application programming interface), so it is not affected by how the web service was developed or which language is used.

If you’re choosing a loosely coupled solution, it means that you’re developing your server application to provide web services that may be called by other server-side applications in addition to an Ajax application. This approach is the most disciplined because it makes no assumption about the capability of the client. A change in the client doesn’t impact the server, and a change in the implementation of the server doesn’t impact the client.

If, however, you’re using a more tightly coupled approach (for example, a Java library such as Google’s Google Web Toolkit (GWT), then the tool itself is going to determine the extent of what you can do with the page or even what’s generated.

For the most part, if you’re adding Ajax to an existing site, you’re going the loosely coupled approach. When you’re starting from scratch, you have the option to use tight coupling as an approach, though you should be cautious in tying the server and client sides so closely together.

Progressive Enhancement Versus Massive Overhaul

As stated earlier, you’re one of the luckier Ajax developers because you have a site or an application that already has all the basic functionality, and now you’re looking to enhance and improve it through the use of Ajax. This might require some preparation ahead of time, but anything done to make the pages better for Ajax also makes the site better.

A summary of what’s been covered in this chapter gives us the following set of steps for simplifying and preparing for your Ajax development:

  1. Validate the existing pages for target XHTML and CSS specifications and make required corrections.

  2. Convert old HTML table layouts to CSS/XHTML, clean up deprecated or out-of-date HTML elements, and convert HTML to XHTML.

  3. Define a plan for adding Ajax effects, including which sections of the site are going to be completely rewritten, which will be modified, and which effects will be incorporated.

  4. Study your readers; determine which pages they access and which tools they use.

  5. Get your web page readers’ involvement, including results of prototype tests.

  6. Create a framework for change; minimize the amount of code by making as much of it reusable as possible. Now would be a good time to consider bringing in a content management system if you aren’t already using one.

Once you’ve formed a plan, defined a framework for rolling out Ajax additions to your site, converted the pages into valid XHTML and CSS, and reduced the CSS variations among browsers, you’re ready to begin adding Ajax.

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