Ajax

Be sure to include the JavaScript libraries in the layout:

<%= javascript_include_tag :defaults %>

Linking to Remote Action

<%= link_to_remote "link", :update => 'some_div',
                           :url => { :action => 'show', :id => post.id } %>

<%= link_to_remote "link", :url => { :action => 'create',
                           :update => { :success => 'good_div',
                                        :failure => 'error_div' },
                           :loading => 'Element.show('spinner'),
                           :complete => 'Element.hide('spinner') } %>

Callbacks

:loading

Called when the remote document is being loaded with data by the browser.

:loaded

Called when the browser has finished loading the remote document.

:interactive

Called when the user can interact with the remote document, even though it has not finished loading.

:success

Called when the XMLHttpRequest is completed, and the HTTP status code is in the 2XX range.

:failure

Called when the XMLHttpRequest is completed, and the HTTP status code is not in the 2XX range.

:complete

Called when the XMLHttpRequest is complete (fires after success/failure if they are present).

You can also specify reactions to return codes directly:

link_to_remote word,
    :url => { :action => "action" },
    404 => "alert('Not found...? Wrong URL...?')",
    :failure => "alert('HTTP Error ' + request.status + '!')"

Ajax Forms

You can create a form that will submit via an XMLHttpRequest instead of a POST request. The parameters are passed exactly the same way (so the controller can use the params method to access the parameters). Fallback for non-JavaScript-enabled browsers can be specified by using ...

Get Rails: Up and Running, 2nd Edition 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.