BUY THIS BOOK
Add to Cart

Print Book $44.99


Add to Cart

PDF $35.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £31.99

What is this?

Looking to Reprint or License this content?


Ajax Design Patterns
Ajax Design Patterns

Book Price: $44.99 USD
£31.99 GBP
PDF Price: $35.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introducing Ajax
BY NOW, YOU'VE PROBABLY USED AJAX ON SITES LIKE GOOGLE MAPS (HTTP://MAPS.GOOGLE.COM) Amazon's A9 search engine (http://a9.com), and Flickr (http://flickr.com). Despite their different domains, all these web sites make heavy use of Ajax. The technology lets them take a great leap forth towards the richness of standard desktop applications, and in a manner which still respects the established conventions of the Web.
No longer are you forced to wait five seconds a web page to reload every time you click on something. Ajax applications change in real-time. They let you drag boxes around instead of clicking on arrows and typing in numbers. They keep page content fresh instead of forcing you to keep hitting Refresh. They show meaningful animations instead of verbose messages.
At the heart of all this is a growing emphasis on web usability. Perhaps you've heard the story of the dancing bear—everyone's impressed with it even though its skills quite frankly wouldn't get the bear into a dance academy; it makes an impression because it can dance and not because of how well it well dances. The Web felt like that at first. Suddenly you could read news from the other side of the world, find hints on some obscure game, purchase a rare book. All valuable activities, regardless of how easy or difficult to perform them. Usability? We don't need no stinkin' usability!
Here's what happened: people discovered that any coder and his dog can build the basic functionality (and you don't always need the coder); amid the rush of B2B companies hyping multimillion dollar auction systems, I recall one CTO bragging that his summer students created the same thing for a few thousand bucks. So if companies in a saturated market can't compete on raw functionality, what can they compete on? The things that matter to users. Most of the companies that have survived and prospered—companies like Google, Amazon, and Yahoo!—avoided feature bloat and promoted simple, though not dumbed-down, interfaces. It's no coincidence that each of these companies have been busy incorporating Ajax features to that end. Each of these monster dotcoms not only uses Ajax, but has actually pioneered some of the concepts described in this book. You can throw Microsoft into that list as well.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajax and the Usable Web
No longer are you forced to wait five seconds a web page to reload every time you click on something. Ajax applications change in real-time. They let you drag boxes around instead of clicking on arrows and typing in numbers. They keep page content fresh instead of forcing you to keep hitting Refresh. They show meaningful animations instead of verbose messages.
At the heart of all this is a growing emphasis on web usability. Perhaps you've heard the story of the dancing bear—everyone's impressed with it even though its skills quite frankly wouldn't get the bear into a dance academy; it makes an impression because it can dance and not because of how well it well dances. The Web felt like that at first. Suddenly you could read news from the other side of the world, find hints on some obscure game, purchase a rare book. All valuable activities, regardless of how easy or difficult to perform them. Usability? We don't need no stinkin' usability!
Here's what happened: people discovered that any coder and his dog can build the basic functionality (and you don't always need the coder); amid the rush of B2B companies hyping multimillion dollar auction systems, I recall one CTO bragging that his summer students created the same thing for a few thousand bucks. So if companies in a saturated market can't compete on raw functionality, what can they compete on? The things that matter to users. Most of the companies that have survived and prospered—companies like Google, Amazon, and Yahoo!—avoided feature bloat and promoted simple, though not dumbed-down, interfaces. It's no coincidence that each of these companies have been busy incorporating Ajax features to that end. Each of these monster dotcoms not only uses Ajax, but has actually pioneered some of the concepts described in this book. You can throw Microsoft into that list as well.
In addition, a whole new generation of companies has risen on the strength of their simple, intuitive applications. 37signals has a suite of tightly focused applications used daily by a passionate user base. With an innovative photo-sharing interface, Flickr built a community of 1 million photo-sharing users in around 18 months. Another recent entrant is Odeo, a podcast manager that works as an easy-to-use web application rather than running in the desktop like most of the competition. Like their giant counterparts, these newcomers are big proponents of Ajax and have helped define the concepts behind many of the Ajax Patterns featured in this book.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Rise of Ajax
On February 18, 2005, Jesse-James Garrett published an online article "Ajax: A New Approach to Web Applications" (http://www.adaptivepath.com/publications/essays/archives/000385.php). The Web was becoming richer and responsive, closing the gap with the desktop. Garrett introduced "Ajax" to label the architecture behind the new generation of rich web apps like Google Maps and Google Suggest. Ajax isn't a plugin, nor a proprietary technology. It's an architectural style—a high-level design pattern—composed of many related technologies and ideas.
Ajax technologies and applications were around before Garrett's article labelled them as such, but the article was a tipping point. Just like when the terms, "object-oriented," "agile development," and "postmodernism" began to be used, a converging trend had been given a buzzworthy umbrella term around which a community could form. "Ajax" gave us a label for the systems that were combining several powerful technologies. With this label established, the development community could suddenly share ideas about how the technologies fit together, debate in blogs about different design approaches, build libraries to support these kind of systems, and catalog common patterns.
Strictly speaking, the term is an acronym —"AJAX," for "Asynchronous JavaScript + XML"—although Garrett has noted that other technologies like CSS and DOM are just as important in the Ajax equation. "Ajax" just happens to roll off the tongue a whole lot easier than "Asynchronous JavaScript+CSS+DOM+XMLHttpRequest." Consistent with his original article, Ajax is generally written "Ajax," not "AJAX." That's a mindset, not mere cosmetic detail, because Ajax is a design style and attitude rather than a precise set of technologies; the technologies are whatever happen to let us build the things we want to build. Throughout this book, I refer to Ajax in terms of what it offers users and their organizations. Here's a working definition:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajaxifying the Web: The Story of Portals
If you Google for "year of the portal", you'll find ample evidence that every year since 1996 has been the year of the portal. It's just around the corner, really. The idea has so much promise: the first thing you see when your browser opens up is a personal homepage with "My News" and "My Mail" and lots of other boxes just about "Me." In short, a page created by Me for Me. So why have they never really taken off? One big factor is that most portal interfaces, frankly, are unusable.
Consider the problems you face in using a legacy-style portal, using Excite.com as an example—many other conventional portals work in a similar manner (Figure 1-1).
Figure 1-1: Excite
  1. Customizing the page is the most critical task, but you have to register first; each of the customization controls on the homepage will close the portal and take you to a completely different registration page.
  2. Adding new "portlets" —the blocks of content—is rather painful. You have to click on Add/Delete Content, which will whisk you off to a tabbed configuration interface. There, you add and delete portlets by updating a list of current portlets.
  3. Customizing an individual portlet—e.g., setting the stocks you're watching—will close the portal and send you to a special configuration page. You've lost the context.
  4. Changing layout doesn't happen directly on the page, but in the configuration area. The layout is managed on a miniature model of the real portal, with titles shown only. (Some portals require repetitive clicking on arrow buttons for layout; fortunately, Excite allows drag-and-drop on the model.)
  5. Volatile content such as news and market information is present on the page, but refreshes occur only occasionally; the smallest allowed period is five minutes. Refreshes force the whole page to be reloaded, which is not only distracting, but also makes it difficult for the user to see what, if anything, just changed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Webifying the Desktop: The Story of Office Applications
Attempts to webify office applications are almost as old as the Web itself. It's now part of computer folklore that Netscape's Marc Andreesen exclaimed, in the mid-1990s, that MS-Windows would be reduced to "a poorly debugged set of device drivers running Netscape Navigator," expecting to herald in a new era of desktop-style applications running inside the browser. The benefits of the Web over desktop apps are clear and abundant—e.g., an ability to access data from any web browser in the world, easy upgrading, no tampering of local machines, and better collaboration. However, there are serious problems too, and the most severe is interface. In the past, it's simply been impossible to produce a portable interface that's good enough to justify switching from the desktop.
This is changing quickly though, thanks to Ajax. A new generation of Ajax office applications (http://innerphaze.homelinux.com/blog/?p=28) are emerging as a serious substitute for MS-Word, Excel, and their desktop contemporaries.
One such offering is Writely, a Google acquisition billed as "The Web Word Processor" (Figure 1-3). Writely rightly avoids slavishly reproducing the desktop word-processing experience and instead aims for a feature set and interface that will work on the Web. The result is something that's as much a turbo-charged wiki as a webified word processor. The list that follows describes some of its features.
Figure 1-3: Writely
  • The content under edit is What-You-See-Is-What-You-Get (WYSIWYG). As you edit, you get to see the final content—color, fonts, layout, and all. The idea is covered in Rich Text Editor (Chapter 14).
  • Writely allows several people to collaborate on the same document at once. Using technology described in the Periodic Refresh (Chapter 10) pattern, it's able to keep updating the document and also the status of other authors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Characteristics of Ajax Applications
Earlier on, Ajax was defined as a technology that "builds on standard web technologies to deliver a rich, responsive, user experience." This shouldn't be seen as a binary thing, because it's useful to think of Ajax as a continuous spectrum—an application that happens to include a Flash widget, or one that avoids using any remoting technology can still be considered "partly" Ajaxian; it's useful to do so if you're designing that system as you can leverage the experience of other Ajax developers, which is the kind of experience encapsulated in the Ajax Patterns. And in documenting the Ajax Patterns, it's certainly useful to learn from applications that aren't "pure Ajax." To that end, the characteristics here are intended as a general guide, but not hard-and-fast rules, for what constitutes an Ajax application.
These days, you'll hear a lot more about "web applications"—or "webapps"—than about "web sites." Driving many modern web projects is the perspective of the browser as a platform and the Web as an operating system. People aren't just buying a book or browsing a manual, but are performing day-to-day work as well as socializing via the browser platform, often working on more critical, complex tasks than in the past. While Ajax can really be applied to anything running inside a browser, it comes into its own with these kinds of systems, where it helps keeps users engaged and productive.
Traditional web sites make you submit a form, wait a few seconds, watch the page redraw, and then start the whole cycle again. That's because the tiniest server interaction, and even the tiniest display change, requires a call to the server, and then a complete page refresh. It's a frustratingly slow and erratic sequence. Ajax changes the model in a few ways. First, JavaScript running inside the browser can manipulate the display directly—you don't have to send a whole new page from the server in order to hide an element or rearrange the page. Second, server interaction can be handled via JavaScript, so you can upload user commands and download new information without any page refresh. Third, user actions such as mouse-clicking and typing can be handled by JavaScript, so the interaction is a lot richer than just filling in a form and hitting Submit. All of these enhancements make Ajax interaction feel faster and more continuous.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Ajax Technologies
Here's a quick rundown of the various technologies involved in Ajax. To begin with, there are several that have always been popular on the Web, which are relatively well-understood by the development community. They are still used in Ajax applications, though sometimes in different ways.
HTML/XHTML
As always, HTML provides the structure of a web page. An Ajax App uses an HTML document to show the initial page, and the document is continuously manipulated to change the display and set up new events. Where possible, its XML-compliant variant, XHTML, should be used in order to make manipulation more robust.
CSS
CSS enriches the display and, thanks to stylesheets, helps separate document structure from style details. Fortunately, browsers are now reasonably consistent in their support for CSS2, so the past few years have seen many web sites shift from table-based layout, which was always something of a hack, to the cleaner, more flexible, CSS-based layout. From our perspective, the great thing about all this is that CSS can easily be manipulated with JavaScript. With just one line of code, you can make an object disappear, move it around the page, or alter its appearance.
HTTP, CGI, Form Submission
As with conventional web applications, Ajax communicates via HTTP. The difference is that instead of returning full pages, the server returns concise results that are then processed in the browser script. Form submission—often with CGI-style URLs—is also used, but again is initiated programmatically, meaning that no page refresh need take place.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Anatomy of a Server Call
At a lower level, how does an Ajax interaction look? Here's a typical sequence of events. Let's begin with the application startup sequence (Figure 1-4):
Figure 1-4: Typical startup sequence
  1. User points browser to Ajax App. The user begins interacting with an Ajax application by visiting it in the usual way; e.g., by following a link or selecting a bookmark.
  2. Browser loads initial content. The browser fills up with initial content sent out by the Ajax application. This includes the initial HTML to be displayed, the CSS to establish styling, and the JavaScript code to manage further interaction. The HTML is sometimes as raw as a general page structure, in which case the initial content will subsequently be pulled down in a second call. The code will usually set up event handlers to dictate how the system should respond to user actions.
Once the application has loaded, further activity will be triggered by events. Following is the typical sequence for each event (Figure 1-5):
Figure 1-5: Typical event-handling sequence
  1. User does something. Most events are triggered by user actions such as mouse clicks. As explained in Dynamic Behavior patterns, JavaScript functions can be registered against particular event types on particular page elements; e.g., you can arrange for the purchase( ) function to be called whenever a shopping item (the page element) is double-clicked (the event type). Thus, the user action will typically cause an event handler to be invoked.
  2. Event handler sends request to server. Certain events require server interaction—for example, the user has just entered some information that should be validated by the server; or the user has just requested some new information.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajax Trends
This book has certainly been a moving target. There were already quite a few Ajax applications available when the "Ajax" term was coined, and the space has since exploded, propelled by the rush of activity in what's come to be known as the "Web 2.0" movement. Each day is bringing fresh ideas to the table, as more and more Ajax applications are released. It's impossible to know where it will all lead, but this section identifies a few future trends and open questions.
Better compatibility across browsers has made rich web development much easier. However, we're at a crossroads now, because the same economic boom that's fuelling Ajax application development is also fuelling innovations in the browsers themselves, leading to a serious risk of diverging technologies.
One group pushing for change is the Web Hypertext Application Technology Working Group (WHAT-WG). The key term here is "Application," as the group is pushing for the Web as a true application platform, a goal that resonates loudly with the aims of Ajax. Under current proposals, rich controls and interaction techniques such as drag-and-drop will enjoy native browser support. All this is good for Ajax developers, but will probably come at the price of compatibility. It's not clear which browsers will support which standards, and there are likely to be major discrepancies in the implementation schedules. Moreover, Microsoft is conspicuous by its absence from WHAT-WG, and it's distinctly possible IE will end up with a very different API for all this functionality. As well as standards endorsed by WHAT-WG and W3C, there will inevitably be browser-specific features to consider as well. Microsoft will continue to evolve its Atlas framework, and it's certainly possible that IE will give Atlas functionality—such as local data storage—that's not available to other browsers.
If browsers do go down the mid-1990s path of diverging APIs, developers will have to decide on appropriate strategy. The options will include: targeting a specific browser (unfortunate, but will sometimes be the most pragmatic choice), ignoring browser-specific features, and relying on compatible plugins for behavior not directly supported by a particular browser.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conclusions
This chapter has introduced the basic technologies of Ajax, provided overviewed characteristic examples, and given some indication of where it's all going, though there will doubtless be some surprises along the way. Even if the "Ajax" name is fairly new, Ajax has been kicking around in various corners of the Net for some time now, and the rest of the book explains what we've learned so far about working with Ajax. In the next chapter, we'll dive head-first into Ajax with a "pattern-led tutorial"—a hands-on introduction to the basic technologies of Ajax as well as the Ajax Patterns that guide their usage.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: A Pattern-Led Tutorial
THIS CHAPTER INTRODUCES AJAX AND THE AJAX PATTERNS IN A THREE-PART TUTORIAL. THE FIRST section is a whirlwind tour of the key technologies, recommended if you've never worked with Ajax before. The second section shows how the higher-level patterns work to enhance a system; if you've already tinkered with Ajax, you might like to jump straight there. The final section proposes some exercises to try on your own.
The online home for this tutorial is http://ajaxify.com/tutorial/, where you'll discover running demos for each example here. To work locally, you'll need a standard PHP installation (version 5 or later) with Apache or a similar web server (no database is required). If you want the completed code, you'll find a downloadable package at the above URL—consult Appendix B for more details on installation. Each section in the tutorial begins with a summary of the corresponding online demo as well as the directory within the code package where you'll find the completed code.
This section includes a few exercises to get up to speed with the basic Ajax technologies. Each section is independent from the others, and each corresponds to a group in the Foundational Technologies Patterns (Part II), which are patterns about the raw technologies on which all Ajax applications are based.
Each demo should live in its own directory, so create a tutorial directory under your server's document root, and then create three fresh directories underneath that:
 cd /apache/docroot (substitute your own document root)
 mkdir tutorial
 cd tutorial
 mkdir display remoting dynamic
For Unix systems, ensure permissions are appropriate for your web server (e.g., make the directories globally readable and executable). Each directory will begin with the same "blank slate" HTML file, index.html. Open up your favorite editor and save the following file to display/index.html, remoting/index.html, and dynamic/index.html
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajax Technologies in a Blink
This section includes a few exercises to get up to speed with the basic Ajax technologies. Each section is independent from the others, and each corresponds to a group in the Foundational Technologies Patterns (Part II), which are patterns about the raw technologies on which all Ajax applications are based.
Each demo should live in its own directory, so create a tutorial directory under your server's document root, and then create three fresh directories underneath that:
 cd /apache/docroot (substitute your own document root)
 mkdir tutorial
 cd tutorial
 mkdir display remoting dynamic
For Unix systems, ensure permissions are appropriate for your web server (e.g., make the directories globally readable and executable). Each directory will begin with the same "blank slate" HTML file, index.html. Open up your favorite editor and save the following file to display/index.html, remoting/index.html, and dynamic/index.html:
  <html>

  <head>
    <title>AjaxPatterns.org - Tutorial</title>
    <script type="text/javascript" src="tutorial.js"></script>
  </head>

  <body>

    <h1>AjaxPatterns Tutorial</h1>

    <div id="sandbox">
    </div>

  </body>
Remember to set file permissions according to the web server's requirements. Now point your browser to one of the new files and check that you can see the above content. The URL should be http://localhost/tutorial/display/ or, failing that, try http://localhost/tutorial/display/index.html.
The HTML file loads the JavaScript file tutorial.js, which isn't there yet. The next three demos will leave the HTML file alone and illustrate Ajax concepts with code in their respective tutorial.js files.

Section 2.1.2.1: Hello World!

To begin, go to the working directory (tutorial/display/). Note that there's an online demo of the application we're going to build at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajaxifying a Web App: One Pattern at a Time
Patterns aren't necessarily about big upfront design; more often, they're used for refactoring and enhancing existing systems. The foundational technologies from the previous section can be seen as techniques for Ajaxifying a conventional web app in addition to being useful for building a new one. In the same way, many of the subsequent patterns can be seen as techniques for improving an existing Ajax App.
Here, we'll look at how a few patterns can be progressively applied to enhance a web app. The conventional app is initially described for comparison, but we really begin building the app at Step 1, where we produce a basic Ajax version. In all, there are four steps. In the packaged code, you'll find the complete code for each step. So if you get lost in the middle of Step 2, you can start Step 3 afresh by taking a clean copy of the completed Step 2 directory. Note that all the application files reside in just the one directory.
There is no working directory (no coding required here). See the location of the completed code within the installation package at /tutorial/ajaxagram/. There's an online demo at http://ajaxify.com/tutorial/ajaxagram/.
Starting on familiar ground, the initial version is a conventional web app—no Ajax here. It takes a word and lists all anagrams; i.e., all possible combinations of the letters (Figure 2-4). For simplicity, there's no dictionary comparison to look for real words, and for the sake of performance, the input field is limited to just five characters. We won't actually build this conventional version, but you might want to peruse the code (in tutorial/ajaxagram/) for comparison with the next Ajaxified version. There are two source files:
anagram.php
The server-side business logic for finding anagrams, described later in the section "Business logic: the anagram web service."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Projects and Katas
Now it's over to you. Here are some suggestions for projects you can work on. You might like to approach these as "Katas" (http://blogs.pragprog.com/cgi-bin/pragdave.cgi/Practices/Kata/), short exercises that you can keep returning to. Alternatively, add all the bells and whistles and make them full-blown projects. Check http://ajaxpatterns.org/Katas for the latest list, and please add links to any of your online efforts.
Two-Person chat
Allow two people to chat in real-time via the browser.
Filesystem navigator
Navigate a server-side filesystem. Bonus points for sanely displaying file contents.
Search portlet
Build a portlet to access your favorite web service, using a Cross-Domain Proxy (Chapter 10) pattern or an On-Demand JavaScript (Chapter 6) pattern if the web service happens to offer a compatible service (such as Yahoo's JSON API). Results should be displayed inside the portlet, without any page refresh.
Drag-And-Drop cart
Create a shopping cart that allows items to be dragged in and out and uploads details to the server. Note that several libraries support drag-and-drop.
Am I Ajax Or Not
Create a clone of AmIHotOrNot.com. Show two random images (or even just random numbers), let the user click on their favorite, and ensure the server records their choice. For bonus points, show scores in the browser; e.g., offer a popup showing the number of "wins" for the two items being displayed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conclusions
The first part of this chapter showed you how to create a basic Ajax application. After performing that section, you should be comfortable about the basics of Display Manipulation (Chapter 5), Web Remoting (Chapter 6), and Dynamic Behavior (Chapter 7. The second part of this chapter introduced a number of the Ajax Patterns—the point is not to understand those patterns in detail, but to get a feel for the sort of thing the patterns do. That is, to see how they build on top of the basic technologies to improve usability, maintainability, and so on. The final part of this chapter suggested several exercises—I recommend you try one or two if you're still coming to grips with Ajax.
It should be clear by now that although Ajax is a great leap forward for the Web, it's no magic bullet. Developers need to tread carefully in order to ensure their Ajax apps are easy to maintain and easy to use. The next chapter summarizes several key principles for Ajax system design and introduces the Ajax Patterns, which offer practical advice on applying those design principles.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Ajax Design: Principles and Patterns
AJAX DOES A LOT FOR WEB USABILITY, HAS ALREADY DELIVERED SOME STUNNING APPLICATIONS, AND IS clearly the "in" thing at this time. But it's no magic bullet. Careful design is always required, and it must be tailored to the technology at hand. By monitoring the state of Ajax applications, we continue to learn about what works and what doesn't, and about how developers are succeeding in their design trade-offs. This chapter explains these lessons at a high level and introduces the patterns, which discuss them in depth.
Ajax is about improving user experience and delivering value to the organizations that own and use web applications. Here, we'll look at the key attributes of an ideal Ajax application. Reality dictates that you'll never get the best of all worlds, so you'll have to make trade-offs based on how important you consider each attribute. The Ajax Patterns are intended to help you deal with these trade-offs.
Usability
Ajax applications should be as intuitive, productive, and fun to use as possible.
Developer productivity
Development should be as efficient as possible, with a clean, maintainable code base.
Efficiency
Ajax applications should consume minimal bandwidth and server resources.
Reliability
Ajax applications should provide accurate information and preserve the integrity of data.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Desirable Attributes of Ajax Applications
Ajax is about improving user experience and delivering value to the organizations that own and use web applications. Here, we'll look at the key attributes of an ideal Ajax application. Reality dictates that you'll never get the best of all worlds, so you'll have to make trade-offs based on how important you consider each attribute. The Ajax Patterns are intended to help you deal with these trade-offs.
Usability
Ajax applications should be as intuitive, productive, and fun to use as possible.
Developer productivity
Development should be as efficient as possible, with a clean, maintainable code base.
Efficiency
Ajax applications should consume minimal bandwidth and server resources.
Reliability
Ajax applications should provide accurate information and preserve the integrity of data.
Privacy
While user-generated data can and should be used to improve the user experience, users' privacy should also be respected, and users should be aware of when and how their data is used.
Accessibility
Ajax applications should work for users with particular disabilities and of different ages and cultural backgrounds.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Designing for Ajax
By studying existing Ajax applications, as well as any relevant precursors, it's been possible to distill a number of important design principles for Ajax, which are shown in this section. The thinking behind the principles was a big influence on the pattern discovery process, and knowing them will help to apply the patterns.
We'll begin by looking at principles of user-centered design, followed by those of software design. Of course, you can never fully separate those concerns, and they're often in conflict with each other. Dealing with those conflicts is really a key concern of the patterns. Incidentally, it's worth checking out a good online resource that takes the opposite perspective: Ajax Mistakes (http://swik.net/Ajax/Ajax+Mistakes) is a long list of Ajax mistakes and gotchas, as well as anti-patterns originally authored by Alex Bosworth and now maintained on a wiki.
Follow web standards
Try hard enough, and you can do some very confusing things with Ajax, even more so as rich graphics become commonplace. Rather than reinventing the Web as we know it, use Ajax to build a "better Web," an enhanced layer over what's already there. Respect the conventions that users are already familiar with.
The browser is not a desktop
Further to the previous principle, Ajax is a richer brand of the traditional web site rather than a webified brand of the traditional desktop. True, desktop widgets like sliders are migrating towards Ajax, but only when they make sense in a web context and often in a modified form. We're also seeing application categories like word processors head online as well, but again, the best products will be those that fit in with the Web rather than blindly replicating the desktop experience.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajax Patterns Overview
The Ajax Patterns show how people have used the design principles effectively in real-world Ajax applications. It might seem funny that we can have so many patterns about Ajax, a term that was coined only a few months before work on these patterns began. However, the ideas are not new; there were many Ajax features on the Web before the term came about to describe them. The healthy Net economy has helped a lot too, with hundreds of new sites now using Ajax, along with powerful tools (RSS, Technorati, Google, and wikis) to locate them as soon as they're available.
With over 60 patterns, it's useful to classify the patterns hierarchically. At a high level, the book is divided into four parts, each corresponding to a different focus area—Foundational Technology, Programming, Functionality and Usability, and Development. Beyond that, each part is divided into several chapters, where each chapter includes related patterns. For instance, Foundational Technology Patterns (Part II), includes Web Remoting (Chapter 6), which includes several patterns for web remoting. Here's a summary of each part:
Foundational Technology patterns (11 patterns)
The foundational technologies are the building blocks that differentiate Ajax from conventional approaches, and this section explains typical usage.
Programming patterns (23 patterns)
These are the features of architecture and code that serve the software design principles listed previously. These include, among other things, design of web services; managing information flow between browser and server; populating the DOM when a response arrives; and optimizing performance.
Functionality and Usability patterns (28 patterns)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Anatomy of a Pattern
All of the patterns follow the same basic format, though certain fields are left out where appropriate. This section explains the meaning of each section.
Evidence
How much real-world evidence exists for the pattern, on a 3-point scale and presented graphically? It's a rather subjective estimate, but use the following icons as a guide:
Suggests the idea is purely speculative
Suggests there's at least a proof-of-concept or an early usage
⊙⊙
Suggests there's a few established examples
⊙⊙⊙
Suggests the pattern is in widespread usage
Tags
Tags—or keywords —help people locate the pattern and get a sense of its focus.
In a Blink
This is a sketch to set the scene for the pattern.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajax Patterns Demos
The Ajax Patterns Demos appear in many patterns as Refactoring Illustrations and also in the Solution section. They're all online at http://ajaxify.com/run/, and it would be worth trying them out. In addition, the full code base can be downloaded from that location; its installation is explained in the Appendix B. It includes the demos as well as completed code for Chapter 2. Note the demos have been tested on Firefox 1.5 and IE6, though most of them work on comparable browsers as well.
The server-side code is all PHP, but most of it is fairly trivial, so it should be fairly easy for all programmers to comprehend. PHP was chosen as it's quite easy for anyone to set up, on any platform. Also, the language itself is fairly "generic" in that anyone with web development experience should have no difficulty following the code.
The demos are organized around a refactoring theme. For most of the examples, there is an initial, "embryonic," Ajaxian application. Then, several parallel refactorings are applied to the same demo, each in a separate subdirectory. And each of these refactorings may have a further refactoring applied, contained in a deeper subdirectory. A tree structure emerges on the site, with each application having evolved in different ways.
For example, look at the evolution of Finite Cache Sum Demo (http://www.ajaxify.com/run/sum/xml/cached/expiry/), which has the path /sum/xml/cached/expiry/.
/sum/
First, there is the basic demo at /sum/. Enter some numbers and the server responds with a sum. As a basic Ajaxian application—with no form submission involved—there are some foundational technologies illustrated here, but that's about it.
/sum/xml/
Next, the sum is refactored to receive results in XML form, as a demo is done for the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conclusions
This chapter has covered how people are designing for Ajax and introduced the Ajax Patterns. The pattern language (just like Ajax itself) isn't a magic bullet, but a tool intended to improve your mastery of Ajax web development. You can use it as a reference for "quick-fix" problem solving, but you probably gain more if you also treat it as an educational resource to learn more about the recurring problems and solutions in Ajax. The remainder of this book constitutes the patterns themselves, divided into four parts according to their area of concern—Foundational Technologies, Programming, Functionality and Usability, and Development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Ajax App
THIS CHAPTER CONTAINS JUST A SINGLE PATTERN, THE ROOT FOR THE ENTIRE PATTERN LANGUAGE: Ajax App.
⊙⊙⊙ Ajax, Balanced, Client-SOA, DHTML, Fast, Fat, Interactive, Platform, RichInternetApplication, Rich, Thick, Web2.0, and WebApp
Figure 4-1: Ajax App
Pam's begun entering staff appraisals into a new Ajax App. She's pleased to see the data entry is much faster: fields are validated as soon as they're filled out, searches are integrated into the form rather than in annoying popups, and the remaining form fields keep mutating to reflect what she's entered so far.
How can you create a rich application?
See Chapter 1 for more details on the forces driving Ajax, which are summarized here.
  • Users like working and playing in the browser and are now more willing to keep their data online, but are nonetheless frustrated with conventional "click 'n' wait" interfaces.
  • Companies like web apps running on their Intranets because it makes deployment much easier, but they continue to be burned by unusable web apps that don't deliver the same value as a comparable desktop app.
  • Developers are now well-versed in the basic patterns of web architecture and ready to take on new challenges.
  • Technology has opened up new opportunities for the Web: broadband and beyond is becoming ubiquitous in many countries; servers can process huge quantities of requests per second; and storage is growing to the point where it's feasible for individuals to host most of their personal data online.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ajax App
⊙⊙⊙ Ajax, Balanced, Client-SOA, DHTML, Fast, Fat, Interactive, Platform, RichInternetApplication, Rich, Thick, Web2.0, and WebApp
Figure 4-1: Ajax App
Pam's begun entering staff appraisals into a new Ajax App. She's pleased to see the data entry is much faster: fields are validated as soon as they're filled out, searches are integrated into the form rather than in annoying popups, and the remaining form fields keep mutating to reflect what she's entered so far.
How can you create a rich application?
See Chapter 1 for more details on the forces driving Ajax, which are summarized here.
  • Users like working and playing in the browser and are now more willing to keep their data online, but are nonetheless frustrated with conventional "click 'n' wait" interfaces.
  • Companies like web apps running on their Intranets because it makes deployment much easier, but they continue to be burned by unusable web apps that don't deliver the same value as a comparable desktop app.
  • Developers are now well-versed in the basic patterns of web architecture and ready to take on new challenges.
  • Technology has opened up new opportunities for the Web: broadband and beyond is becoming ubiquitous in many countries; servers can process huge quantities of requests per second; and storage is growing to the point where it's feasible for individuals to host most of their personal data online.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Display Manipulation
FOR AN END USER, THE MOST OBVIOUS THING ABOUT AJAX IS ITS VISUAL APPEARANCE. AJAX APPS TEND to look richer, and the interface tends to update smoothly, more like a desktop app than a conventional web app. This chapter describes the two main technologies for updating the user interface. Display Morphing focuses on changes to a single element, while Page Rearrangement involves changes to the page structure. Along the way, we'll look at the Document Object Model (DOM). DOM manipulation is key to many of the Ajax Patterns.
⊙⊙⊙ Display, DOM, Graphics, GUI, Morph, Page, Paint, Reference, Rich
Figure 5-1: Display Morphing
Stuart is answering a question in an online quiz, with a countdown box showing how much time remains. The countdown label changes each second, and the color gradually shifts from green to red as the countdown proceeds.
How can you dynamically update display elements?
  • As the user's task and context changes, applications need to present different types of information.
  • As information the user is working on changes, information being displayed becomes stale.
  • Stale information is a big problem in conventional web apps. Because the information cannot change until it's out of date, you sometimes see disclaimers such as "May Be Out of Date" or instructions like "Click to Refresh."
  • Submitting and redrawing the entire page interrupts the user's flow.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Display Morphing