Home arrow Ruby-on-Rails arrow Page 2 - Web Forms and Ruby on Rails

Web Forms and Ruby on Rails

In this fifth article of a six-part series covering web development and Ruby on Rails, you'll learn how to create an AJAX form and more. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 4 stars4 stars4 stars4 stars4 stars / 33
April 19, 2007
  1. · Web Forms and Ruby on Rails
  2. · 15.17 Creating an Ajax Form
  3. · 15.18 Exposing Web Services on Your Web Site
  4. · 15.19 Sending Mail with Rails

print this article

Web Forms and Ruby on Rails - 15.17 Creating an Ajax Form
(Page 2 of 4 )


You want to build a web application that's responsive and easy to use. You don't want your users to spend lots of time waiting around for the browser to redraw the screen.


You can use JavaScript to make the browser's XMLHTTPRequest object send data to the server, without dragging the user through the familiar (but slow) page refresh. This technique is called Ajax,* and Rails makes it easy to use Ajax without writing or knowing any JavaScript.

Before you can do Ajax in your web application, you must edit your application's main layout template so that it calls the javascript_include_tag method within its <HEAD> tag. This is the same change made in Recipe 15.15:

  <!-- app/views/layouts/application.rhtml -->

      <title>My Web App</title>
      <%= javascript_include_tag "prototype", "effects" %>
      <%= @content_for_layout %>

Let's change the application from Recipe 15.16 so that the new action is AJAX-enabled (if you followed that recipe all the way through, and made the edit action use new.rhtml instead of edit.rhtml, you'll need to undo that change and make edit use its own view template).

We'll start with the view template. Edit app/views/items/new.rhtml to look like this:

  <!-- app/views/items/new.rhtml -->
<div id="show_item"></div>

        <%= form_remote_tag :url => { :action => :create },
        :update => "show_item",
        :complete => visual_effect(:highlight, "show_item") %>

  Name: <%= text_field "item", "name"
%><br />
Value: <%= text_field "item", "value"
%><br />
<%= submit_tag %>
 <%= end_form_tag %>

Those small changes make a standard HTML form into an Ajax form. The main difference is that we call form_remote_tag instead of form_tag. The other differences are the arguments we pass into that method.

The first change is that we put the :action parameter inside a hash passed into the :url option. Ajax forms have more options associated with them than a normal form, so you can't describe its form action as simply as you can with form_tag.

When the user clicks the submit button, the form values are serialized and sent to the destination action (in this case, create) in the background. The create action processes the form submission as before, and returns a snippet of HTML.

What happens to this HTML? That's what the :update option is for. It tells Rails to take the result of the form submission, and stick it into the element with the HTML ID of "show_item". This is why we added that <div id="show_item"> tag to the top of the template: that's where the response from the server goes.

The last change to the new.rhtml view is the :complete option. This is a callback argument: it lets you specify a string of JavaScript code that will be run once an Ajax request is complete. We use it to highlight the response from the server once it shows up.

That's the view. We also need to modify the create action in the controller so that when you make an Ajax form submission, the server returns a snippet of HTML. This is the snippet that's inserted into the "show_item" element on the browser side. If you make a regular (nonAjax) form submission, the server can behave as it does in Recipe 15.16, and send an HTTP redirect.* Here's what the controller class needs to look like:

  class ItemsController < ApplicationController
    def new
      @item = Item.new

    def create
      @item = Item.create(params[:item])
       if request.xml_http_request?
       render :action => 'show', :layout => false
        redirect_to :action => 'edit', :id => @item.id

    def edit
      @item = Item.find(params[:id])

      if request.post?
         redirect_to :action => 'edit', :id => @item.id

This code references a new view, show. It's the tiny HTML snippet that's returned by the server, and stuck into the "show_element" tag by the web browser. We need to define it:

  <!-- app/views/items/show.rhtml -->

  Your most recently created item:<br />
  Name: <%= @item.name %><br />
  Value: <%= @item.value %><br />

Now when you use http://localhost:3000/items/new to add new items to the data base, you won't be redirected to the edit action. You'll stay on the new page, and the results of your form submission will be displayed above the form. This makes it easy to create many new items at once.


Recipe 15.16 shows how to submit data to a form in the traditional way: the user clicks a "submit" button, the browser sends a request to the server, the server returns a response page, and the browser renders the response page.

Recently, sites like Gmail and Google Maps have popularized techniques for sending and receiving data without a page refresh. Collectively, these techniques are called Ajax. Ajax is a very useful tool for improving your application's response time and usability.

An Ajax request is a real HTTP request to one of your application's actions, and you can deal with it as you would any other request. Most of the time, though, you won't be returning a full HTML page. You'll just be returning a snippet of data. The web browser will be sending the Ajax request in the context of a full web page (which you served up earlier) that knows how to handle the response snippet.

You can define JavaScript callbacks at several points throughout the lifecycle of an Ajax request. One callback, :complete, was used above to highlight the snippet after inserting it into the page. This table lists the other callbacks.

Callback name Callback description
:loading Called when the web browser begins to load the remote document.
:loaded Called when the browser has finished loading the remote document.
:interactive Called when the user can interact with the remote document, even if it has not finished loading.
:success Called when the XMLHttpRequest is completed, and the HTTP status code is in the 2XX range.

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


Called when the XMLHttpRequest is complete. If :success and/or :failure are also present, runs after they do.

blog comments powered by Disqus

- Ruby-on-Rails Faces Second Security Flaw in ...
- Ruby 2.0 Prepped for February 2013 Release
- Why LinkedIn Switched from Ruby on Rails
- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials