O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

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

15.17. Creating an Ajax Form

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,[6] 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 AJAXenabled (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: ...

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