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

Ajax Links

Now that we’ve got a decent canvas, we can add some Ajax to the mix. Change your index.html template to look like this:

<%= link_to_remote "Check Time",
    :update => 'current_time',
    :url    => { :action => 'get_time' } %>
<div id="current_time"></div>

We’ve turned link_to to link_to_remote and added a new option, :update. The value of :update refers to the HTML element ID where the Ajax response should be inserted—in this case, a DIV. The generated HTML looks like this:

<a href="#"
   onclick="new Ajax.Updater('current_time', '/chapter3/get_time',
               {asynchronous:true, evalScripts:true});
            return false;">Check Time</a>
<div id="current_time"></div>

Take a look at the generated HTML, and you’ll see it uses Prototype’s Ajax.Updater method. All the Rails Ajax helpers work this same way: they are Ruby methods, embedded in HTML templates, generating JavaScript, calling Prototype.

Tip

You may have noticed a red flag in the generated HTML link: href="#". While technically valid HTML, this kind of “link to nowhere” is generally a bad practice. If the user has JavaScript turned off, or a search engine is indexing the page, the link will be meaningless. Whenever possible, it’s a good idea to provide a useful link, as a fallback for non-Ajax browsers. Chapter 6 covers the idea of degradability in more detail.

The essential mechanism of Ajax links is the onclick attribute, which is a way to hijack the behavior of a link. When an onclick is provided, the browser will evaluate it before following ...

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