O'Reilly logo

Ajax on Rails by Scott Raymond

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

What Ajax Is

Ajax represents a significant shift in how the Web is built—and even in how it’s conceived. But it’s a really simple idea: web pages, already loaded in a browser, can talk with the server and potentially change themselves as a result. So instead of a form submission causing a whole new page to load, an Ajax form submission happens in the background and just updates the current page in place—no refresh, no flash of white as the page changes, no change in the address bar. That’s the essence of Ajax, in the concrete. It’s really that simple! While keeping in mind that simple, concrete definition of Ajax, let’s take a minute to look at Ajax in a more abstract way. First, consider how the Web traditionally works.

The Traditional Model

Think about the way the Web usually works, without Ajax. First, the browser creates an HTTP request for something on the server, say /page1.html. Figure 1-1 shows the life cycle of the request.

The traditional (non-Ajax) request model

Figure 1-1. The traditional (non-Ajax) request model

In this model, the server sends back a response containing a page—perhaps including a header area with a logo, a sidebar containing navigation, and a footer. With the next click on a link or button, the whole cycle repeats for /page2.html: a new connection to the server, a new request, and a new page. Even the parts of the page that haven’t changed (say, the header and sidebar) are sent over the wire again. The process of sending the request, waiting for the response, and rendering a new page might take a while, and once the user has clicked, he’s effectively committed to that wait before he can proceed.

This model works fine, to a point. In fact, when the nature of your site is primarily document-centric, it’s quite desirable. But when developing web applications, it’s a bit heavy—small interactions that ought to feel responsive are sluggish instead. For example, imagine a web application for managing to-do lists. If simply checking an item off the list causes the entire page to be re-fetched and rendered, the cause and the effect are pretty disproportionate.

The Ajax Model

Remember how simple Ajax is in concrete form: it’s just pages talking with the server without a full refresh. With that in mind, contrast the traditional request model with the Ajax model, as seen in Figure 1-2.

The Ajax request model

Figure 1-2. The Ajax request model

In the Ajax model, the action on the client side is split into two logical parts—a user interface layer and an Ajax layer. When a user clicks a link, or submits a form, that input is handed to the Ajax layer, which could then interact with the server, and update the UI layer as appropriate.

This is the conceptual cornerstone of Ajax: the UI interaction is logically separated from the network interaction.

There are a few important points to draw from the diagram of the Ajax model:

  • The Ajax layer might not need to call the server (for example, it might only need to perform simple form validation, which could be handled completely client-side).

  • Because the requests between the Ajax layer and the server are for small pieces of information rather than complete pages, there is often less database interaction, rendering time, and data to transport—making the round-trip time for the request shorter.

  • The UI layer is not directly dependent on the server’s responses, so the user can continue to interact with a page while activity is happening in the background. This means that, for some interactions, the user’s wait time is effectively zero.

  • Communication between the page and the server doesn’t necessarily imply that Ajax always results in a change to the UI. For example, some applications use Ajax to notify the server about the user’s interactions with the page, but don’t do anything with the server’s response.

These fundamental differences from the traditional request cycle are what enable Ajax applications to be significantly more responsive. And that means that web applications can start to perform like desktop applications—and retain all the benefits of being hosted, rather than installed locally.

It’s Actually Pretty Easy

If the Ajax model just described sounds like a lot of work, don’t fret. In practice, Ajax is very easy to be productive with, especially in Rails. To pique your interest and whet your appetite, here’s a tiny example of how much can be accomplished with very little code. Don’t worry if the syntax is unfamiliar—just focus on the intent of the code.

There are two files in this example: pique.rhtml uses HTML with embedded Ruby statements to create a simple “Ajaxified” form; whet.rjs receives the form submission and updates the page in response. Here’s the first file, pique.rhtml:

<%= form_remote_tag :url => { :action => 'whet' } %>
  Enter your name: <%= text_field_tag :name %>
  <%= submit_tag "Greet Me" %>
<%= end_form_tag %>
<h2 id="greeting" style="display: none"></h2>

This code creates a familiar-looking HTML form with one field and a submit button, as well as a hidden HTML heading (see Figure 1-3). When the form is submitted, it will use Ajax to invoke the second file, whet.rjs:

A simple Ajax form

Figure 1-3. A simple Ajax form

page[:greeting].update "Greetings, " + params[:name]
page[:greeting].visual_effect :grow

These four lines of code pack a wallop—they are instructions telling the page how to update itself. Taking it one line at a time, the instructions are:

  1. Hide the element called “greeting” (in case it’s not already hidden).

  2. Update the element—that is, replace the text inside the tags with some new text.

  3. Show it again, animating it onto the screen with a zoom effect.

  4. Find the first form on the page and reset it, so that the input field is blank again.

The end result after submitting the form is shown in Figure 1-4. Note that the address bar hasn’t changed—that’s because the page wasn’t replaced with a new one, it was just updated in place.

After submitting the Ajax form

Figure 1-4. After submitting the Ajax form

If you’re surprised at how little work is needed to get such impressive results, welcome to Ajax on Rails.

The Eras of Web Development

The web has only been a mass phenomenon since about 1995, so for many developers, it’s not hard to remember how we got here. Still, in order to understand the significance of Ajax, it’s valuable to look back at the big themes. At the risk of being overly grand, let’s compare the history of the Web to the history of the world. Historians organize time into a handful of eras—long periods with distinctive, defining characteristics. With a bit of hyperbole and broad-brushing, the same divisions can be used to understand the eras of web development.

First, there’s pre-history, the earliest days, before writing was invented, before civilization. In web terms, Tim Berners-Lee sparked the big bang with his WorldWideWeb program. His vision centered on hypertext, the idea that individual phrases in a document could be linked to other documents. This first incarnation of the Web would hardly be recognized today. All text—no images, colors, or font choices. All static—no forms, CGI, or JavaScript. And in terms of content, almost all academic and scientific—no e-commerce, no advertisements, and no news. Despite the huge differences, however, the three pillars of the Web were in place: HTTP, HTML, and URLs.

The next major milestone in world history was the transition to the ancient era—the dawn of civilization. People formed ever-larger communities, and they developed increasingly complex systems and institutions to support the growth. For our purposes, the ancient Web begins with Mosaic, the first web browser to really show the Web’s potential. Its biggest innovation: the introduction of the <img> element. Suddenly, the Web burst into color, and with color came personality. Personal home pages became de rigueur, and the pulse of the Web quickened.

Next came the Middle Ages—that long, vibrant period of migration, growth, and invention. The Web analog might be summed up as “the David Siegel ages”—the Web designer who popularized the “single-pixel GIF trick” and deeply nested HTML tables. This era also saw the first <font>, the birth of the banner ad, and the explosion of e-commerce.

Most web developers today live in the modern era. The biggest signpost is standards: CSS has come to the fore, and web designers are un-learning the markup hacks that are no longer necessary. Although far from perfect, the most popular browsers are increasingly compatible and reliable.

Now, the stage is set for the latest act, the postmodern era. Old assumptions and institutions are questioned, which generates exciting energy, along with turmoil. In web terms, the biggest keyword here is Ajax. The core idea of Ajax is that the Web is no longer page-centric. Rather, individual chunks of a page are dynamic and malleable, independent of each other. It’s a simple concept, but it has profound implications, and requires rethinking our assumptions about how the Web should be built.

History of Ajax

Although the name is relatively new, the ideas behind Ajax have been brewing for some years. Variously called web remoting and remote scripting, the idea is simply communication between the web client and server at a subpage level. There are several ways to accomplish that goal. One of the earliest was Java applets, but that approach suffered under the weight of slow Java implementations and inadequate cross-browser compatibility. A more popular trick uses hidden HTML frames—JavaScript is used to load new data into a hidden frame, before it’s pulled out and parsed. Some high-profile sites (such as Google Maps) use this technique, although it has drawbacks, such as no reliable error detection.

Today, the most popular solution for building Ajax applications is an unfortunately named object, XMLHttpRequest. In its original implementation by Microsoft, it was an ActiveX object called XMLHTTP. Since its debut in Internet Explorer, other browsers have cloned it as XMLHttpRequest, including Firefox (and its relatives, Netscape and Mozilla), Safari, and Opera. Of course, this wouldn’t be the Web if each browser didn’t have its own pesky quirks. But nonetheless, most major browsers today have good support for XMLHttpRequest—and that opens up a lot of possibilities.

An oft-heard complaint about the term Ajax is that it’s merely a new marketing term for old techniques. And in fact, that’s exactly correct. When Jesse James Garrett coined Ajax (http://www.adaptivepath.com/publications/essays/archives/000385.php), it was explicitly for the purpose of putting an accessible label on a broad swath of technologies that had been in use for years. After all, when you are pitching an idea to a client or a boss, complex solutions need a simple term that makes it easy to talk about.

Ajax: Neither Asynchronous nor XML. Discuss.

Although it’s not strictly an acronym, let’s break down Ajax into its literal parts: asynchronous, JavaScript, and XML.

Asynchronous refers to the fact that, by default, XMLHttpRequest calls are nonblocking; that is, the browser can initiate a request, and then keep executing code without waiting for the response to come back. If it weren’t for that fact, the Ajax experience would be far less pleasant—if the network or server were slow, your browser would seem to freeze while it waited on a response. Asynchronicity is essential to providing a smooth user experience, but it can complicate the programming. Occasionally, there are circumstances when you don’t want Ajax calls to be asynchronous, when the user shouldn’t have any interaction until a response is returned from the server. XMLHttpRequest and Rails handle that just fine. So, despite its name, Ajax is not necessarily asynchronous.

The J in Ajax stands for JavaScript. JavaScript is a powerful language that is often abused and unfairly maligned. It’s the only scripting language that’s supported more-or-less uniformly across all modern browsers, so it’s immensely useful for manipulating web pages on the client side.

Originally called LiveScript, marketing folks at Netscape changed the name in order to associate it with Java—even though the two languages have no real relationship. These days, the official, vendor-neutral name of the language is ECMAScript, but in popular usage JavaScript has stuck.

JavaScript has a bad reputation among many web developers, because it’s associated with amateurish, brittle, cut-and-paste scripts. Historically, development-support tools for JavaScript, such as debuggers and loggers, also have been weak, making JavaScript development frustrating at best. The good news is that JavaScript can be far nicer than its reputation would suggest. With a combination of quality libraries, development support tools, and some practices for writing solid code, JavaScript can be a surprisingly agreeable platform.

Although JavaScript may be the most ubiquitous language for client-side scripting, it’s not the only option. Internet Explorer supports Visual Basic scripts in the browser, and Flash provides widely deployed, cross-platform scripting. And both environments allow calls to the server, meaning that the J in Ajax isn’t a necessity either.

That brings us to the X, as in XML. As you can probably guess, it turns out this isn’t really an Ajax absolute either. The XMLHttpRequest object can easily handle content of any type— XML, HTML, plain text, images, anything. In fact, as we’ll see, Rails applications rarely request XML data via Ajax. Most often, Rails apps use HTML and JavaScript as the format for Ajax responses.

A couple of other things contribute to the essence of Ajax as well, namely the Document Object Model (DOM) and CSS. The DOM is a language-neutral interface for accessing HTML and XML documents. Before the DOM was standardized, each browser had its own methods for accessing page elements from JavaScript. CSS is essential for allowing appealing graphic design without sacrificing the semantic structure of HTML documents.

So, if you’re a literalist, feel free to refer to this book as [AS]|[JFV]A[XHJ] on Rails. But I’d suggest a redefinition of Ajax in terms of the problems it solves, rather than the exact technologies used. For the purposes of this book, Ajax is the use of browser-native technologies (e.g., JavaScript and the DOM, but not Flash) to decouple user interaction processes from server communication processes.

It’s worth noting that this definition of Ajax isn’t universally accepted. Many developers feel that Ajax necessarily implies use of XMLHttpRequest, and that any other use of the word is a conflation with plain JavaScript. But even Jesse James Garrett’s article introducing the term cited client-side form validation as an example of Ajax.

Regardless of what words are used, the important thing is using the tools at hand to provide the best possible experience for the user—and that’s the goal of this book.

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