Preface

Ajax, a term coined in 2005 to describe the combination of a group of popular web technologies, has been an instant hit in the software world. Instant success can raise many doubts, but it would be a mistake to view this software model as simply the latest “next big thing” to make a big splash and then vanish into the ether of the Web.

Why? First of all, Ajax’s interweaved technologies, including JavaScript, the Document Object Model (DOM), and Cascading Style Sheets (CSS), live in the world of the Web, where new information and technologies hit millions of people in milliseconds. If the technique represents an interesting idea with practical merit, a good probability exists that developers will at least dip their toes into the technology’s waters, if not immediately add the new tool to their code arsenals. Second, the Ajax family of techniques are already well known and open source, or free of charge; therefore, few barriers exist to trying them out for at least a prototype version of new software. Third, a number of useful, well-known applications are based on Ajax, such as Flickr and Gmail. Fourth, web users are already accustomed to an Ajax application’s desktop-like experience, where the application can make client/server connections without completely changing the browser page.

There are numerous other reasons why Ajax is here to stay, such as the excellent support for JavaScript, CSS, and DOM provided by modern browsers such as Firefox, as well as the pros and cons of using Macromedia Flash for Rich Internet Applications instead.

Building Single-Page Applications

The “single-page application” represented by Ajax, with client/server connections that do not interrupt the user’s experience and dynamically change elements in different web page regions, is appropriate for numerous uses, such as blogs, learning tools, online newsletters, and small web portals or communities. Many of these types of sites are already built using Ajax techniques. Ajax can also improve the user experience in large web-based client/server applications that extend beyond the single-page model.

The time between the conception of this book and the writing of this preface has seen Ajax morph into a software platform that dominates headlines on the Web, not to mention the birth of new acronyms such as Ajaj (Asynchronous JavaScript and JSON) and lingo such as “Ajaxy” (as in an Ajaxy server connection). Software innovations and human language seem to share the same organic dynamic.

Explaining Ajax

Ajax Hacks was written by yours truly and seven different contributors, many of whom are among the innovators, bloggers, and early adopters who helped give Ajax and its open source tools the boost it enjoys today. They are senior web engineers and developers whose homes stretch from Bangalore to San Francisco, a scope reflecting the diverse and serendipitous nature by which the writers found this book and the book discovered its writers. (See the Credits for more details on these writers.)

Ajax Hacks collects not only dozens of easy-to-grasp, cutting-edge explorations of Ajax technology, such as Google/Yahoo! mapping mash-ups, drag-and-drop bookstores, and single-page web services apps, but a large number of hacks that represent practical advice for Ajax developers. Ajax Hacks also introduces JavaScript newbies and aficionados alike to useful code libraries, including Prototype, Rico, and script.aculo.us. Chapter 7 focuses on a practical and new web application framework with excellent Ajax tools including Ruby on Rails.

A number of the contributions are hacks in the original, clever sense of the term, exploring topics such as using algorithms and Flash objects to simulate a browser history list and store Ajax-related data offline, configuring Apache to fix the XMLHttpRequest cross-domain restrictions, running a search engine inside your browser, and mashing up Yahoo! Maps with a location-to-URL service called GeoURL.

Some of the contributed hacks illustrate cool web controls and embedded scripts, such as a hack that scripts an auto-complete field from scratch, a hack that creates JavaScript bookmarklets that do not have size limitations, and another that creates an RSS feed reader for an Ajax application. These are hacks that push the envelope, just as we approach the cusp of this web model’s formulation. At the same time, web developers can adapt a number of this book’s hacks, some of which are distributed as open source libraries, for their own applications.

How to Use This Book

You can read this book from cover to cover if you like, but for the most part, each hack stands on its own, so feel free to browse and jump to the different sections that interest you most. If there’s a prerequisite you need to know about, a cross reference will guide you to the right hack. So, feel free to browse, flipping around to whatever sections interest you most.

How This Book Is Organized

The book is divided into several chapters, organized by subject:

Chapter 1, Ajax Basics

What is Ajax? This chapter begins with a synopsis of the group of well-known technologies that make up Ajax. The chapter’s hacks introduce the XMLHttpRequest JavaScript object and its properties and methods, then delve into the meat of the matter, such as sending GET and POST requests, as well as receiving data in plain text, XML, and JSON format. This chapter also illustrates the dynamic scripting of CSS styles in Ajax applications. Let the users change the colors and fonts inside the browser page!

Chapter 2, Web Forms

Web forms have certainly changed in the Ajax world. As revealed in this chapter’s hacks, it is typical now to submit form data and to build form widgets such as select lists and checkbox groups using server data fetched in the background with XMLHttpRequest. Because the page doesn’t have to be completely rebuilt from a server response, the user experiences few application delays. These hacks show how to submit text from form fields and textareas and display server values in those fields, without making the user click a submit button. The hacks also generate various elements, such as select lists and unordered lists, using XMLHttpRequest and data that is dynamically accessed from a server.

Chapter 3, Validation

Ajax applications can cut down on server hits by validating the format of email addresses, credit card numbers, zip codes, and other types of data that users enter into web forms before sending the data. A server component is obviously necessary for final credit card validation in a real-world application; however, the application may implement a “first layer of defense,” as in these hacks, by validating the formats of text-field values with JavaScript regular expressions.

Chapter 4, Power Hacks for Web Developers

Web developers have never had cooler, easier-to-work-with tools than the Yahoo! and Google web APIs. This chapter includes a mash-up of Google Maps, Yahoo! Maps, and Yahoo! driving directions, as well as a software interaction involving Yahoo! Maps and a location-to-URL service called GeoURL. It also features more prosaic, pragmatic web hacks, such as sending an email with XMLHttpRequest; viewing, creating, and sending HTTP cookies with client-side script; fetching a postal code dynamically without altering the web page; as well as discovering and displaying the browser’s locale information.

Chapter 5, Direct Web Remoting (DWR) for Java Jocks

DWR is a nifty toolkit that allows developers to make remote calls to Java server objects from JavaScript, without any Java applets or plug-ins. DWR uses Ajax requests behind the scenes; the toolkit’s users, however, do not have to deal with XMLHttpRequest programming. These hacks populate select lists from Java arrays and Maps; call custom Java objects from their JavaScript proxies or counterparts; and use JavaScript objects to call built-in Java objects. This chapter is a treat for developers who are immersed in both Java and JavaScript.

Chapter 6, Hack Ajax with the Prototype and Rico Libraries

The hacks in this chapter use Prototype, a cool open source JavaScript library that includes its own Ajax tools. You’ll see how to update DOM elements in a web page with server data using Prototype’s Ajax.Updater object, and how to use the PeriodicalExecuter object to execute Ajax requests at timed intervals while another “observer” object monitors a text field for changes (imagine: a user enters data into text fields, and a JavaScript object automatically sends the data off to persistent server storage whenever the field value changes). Another hack in this chapter uses the open source library Rico in a Weather.com web services application. Finally, the chapter’s last hack sets up a drag-and-drop bookstore, also using Rico.

Chapter 7, Work with Ajax and Ruby on Rails

Learn Ruby on Rails! Ruby on Rails (RoR) is an efficient and well-designed web application framework, based on the Model-View-Controller design pattern, that made its debut in 2005. This chapter begins with a simple hack that helps you get up and running with RoR, then moves on to several hacks that illustrate RoR’s Ajax tools. Each hack is a web application task written in Ruby; for example, one of the hacks monitors a server connection and displays the status in the client. RoR bundles Prototype with the framework, then wraps the setup of the Ajax objects into its own easy-to-learn, embedded script language. Get ready to read a lot of Ruby code, a treat for those who may be new to this elegant and powerful tool!

Chapter 8, Savor the script.aculo.us JavaScript Library

script.aculo.us is another open source JavaScript library built on Prototype. It offers a broad menu of useful effects and controls for developers. These hacks create a Mac OS X–style login box that “shakes” in response to invalid logins; an auto-complete field based on a script.aculo.us object; a control that allows the user to edit textual content in the browser and then save the changes on a server, without a web page round trip; and, just for fun, a web form that disappears in a puff of smoke when it’s submitted.

Chapter 9, Options and Efficiencies

These hacks provide several tips for real-world Ajax developers. Ironically, several hacks illustrate how to avoid using XMLHttpRequest to hit the server: you’ll see how to run a search engine inside the browser, cache data with JavaScript, and “fix” the browser back button in an Ajax application by internally storing and accessing state. These hacks also recommend ways to combine code libraries to increase download speed, obfuscate or partially obscure JavaScript code to protect proprietary scripting, set a timer for aborting an Ajax request, as well as dynamically request data in JavaScript Object Notation (JSON) format using the HTML script tag.

Conventions Used in This Book

The following is a list of the typographical conventions used in this book:

Italics

Used to indicate URLs, filenames, filename extensions, and directory/folder names, e.g., a path in the filesystem appears as /Developer/Applications

Constant width

Used to show code examples, the contents of files, console output, as well as the names of variables, commands, and other code excerpts

Constant width bold

Used to highlight portions of code

Gray type

Used to indicate a cross reference within the text

You should pay special attention to notes set apart from the text with the following icons:

Tip

This is a tip, suggestion, or general note. It contains useful supplementary information about the topic at hand.

Warning

This is a warning or note of caution, often indicating that something might break if you’re not careful, possibly quite badly.

The thermometer icons, found next to each hack, indicate the relative complexity of the hack:

Whenever possible, the hacks in this book are not platform-specific, which means you can use them on Linux, Macintosh, and Windows machines. However, some things are possible only on a particular platform.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Ajax Hacks by Bruce Perry. Copyright 2006 O’Reilly Media, Inc., 0-596-10169-4.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

O’Reilly Safari

When you see a Safari® icon in your favorite technology book, it means the book is available online through O’Reilly Safari.

Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top technology books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at http://oreilly.com/safari.

How to Contact Us

We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). As a reader of this book, you can help us to improve future editions by sending us your feedback. Please let us know about any errors, inaccuracies, bugs, misleading or confusing statements, and typos that you find anywhere in this book.

Please also let us know what we can do to make this book more useful to you. We take your comments seriously and will try to incorporate reasonable suggestions into future editions. You can write to us at:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the Unitd States or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)

To ask technical questions or to comment on the book, send email to:

The web site for Ajax Hacks lists examples, errata, and plans for future editions. You can find this page at:

http://www.oreilly.com/catalog/ajaxhks/

For more information about this book and others, see the O’Reilly web site:

http://www.oreilly.com

Got a Hack?

To explore Hacks books online or to contribute a hack for future titles, visit:

http://hacks.oreilly.com

Get Ajax Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.