SunQuest
 
       Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 2 - Web Forms and Ruby on Rails
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
Moblin 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Web Forms and Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 7
    2007-04-19

    Table of Contents:
  • Web Forms and Ruby on Rails
  • 15.17 Creating an Ajax Form
  • 15.18 Exposing Web Services on Your Web Site
  • 15.19 Sending Mail with Rails

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Web Forms and Ruby on Rails - 15.17 Creating an Ajax Form


    (Page 2 of 4 )

    Problem

    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.

    Solution

    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 -->

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

    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
        end

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

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

          if request.post?
             @item.update_attributes(params[:item])
             redirect_to :action => 'edit', :id => @item.id
         
    end
        end
      end

    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 />
      <hr>

    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.

    Discussion

    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.
    :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. If :success and/or :failure are also present, runs after they do.

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · This article is an excerpt from the "Ruby Cookbook," published by O'Reilly. We hope...
     

    Buy this book now. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops
    - Ruby Conditionals
    - Ruby Operators and Arrays
    - Ruby for the Newbie







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway