Ajax on Rails

Bringing together Ajax and Rails with Prototype

Intelligent flash storage arrays

In an earlier tutorial we discussed Ruby on Rails. Ajax is an XMLHttpRequest-based web technique that you can use to transfer data between a client application and a web server, and which lets you update sections of the web page without reloading it.

Rails supports Ajax functions where a XMLHttpRequest request may be sent to a web server and the XMLHttpRequest response updates the web page. In this article, we’ll develop a Rails Ajax web application which runs against MySQL database.

Rails provides support for Ajax in the Prototype JavaScript Framework, which is a set of methods that return the required JavaScript to implement the method. Some of the methods in the Prototype JavaScript framework are described in Table 1.

Table 1. Rails Prototype JavaScript Methods

Prototype Method Description
form_remote_tag Returns a form tag that will submit a form using XMLHttpRequest.
link_to_remote Returns a link to a remote object that is invoked using XMLHttpRequest
observe_field Observes a form and invokes a specified url using XMLHttptRequest. Updates innerHTML of an element of the specified DOM ID with XMLHttpRequest response text.
observe_form Similar to observe_field, but for a form.
periodically_call_remote Periodically invokes a specified url using XMLHttpRequest and updates a specified div with XMLHttpRequest response text.
submit_to_remote Returns a button input that will submit a form with XMLHttpRequest.
update_element_function Returns a JavaScript function that will update a specified element using XMLHttpRequest.
update_page Updates a web page using XMLHttpRequest.

We will create a rails application, railsapp, and then create a MySQL database table, catalogs, as explained in the Ruby on Rails tutorial. The database.yml configuration file and the migration script, 001_create_catalogs.rb are available in the Resources zip file.

Sending a Request

First, create a controller class and the view template with the following command:

C:/ruby/railsapp>ruby script/generate controller catalog index

A catalog_controller.rb Ruby file is generated in the railsapp/app/controllers directory. A view template, index.rhtml, is created in the railsapp/app/views/catalog directory. HTTP requests are initiated from the view template and processed by the Action Controller framework.

The Ajax functionality is implemented in the Prototype JavaScript framework, so you should include the prototype library with the following declaration in the <head> </head> section of the index.rhtml file:

<%= javascript_include_tag “prototype” %>

A XMLHttpRequest may be initiated using one of the methods described in Table 1. We’ll use the observe_field method. In index.rhtml, a text field is used to specify that a catalog section is polled at a specified frequency and a XMLHttpRequest request is sent to the web server. An article_list div in the web page is then updated with the XMLHttpRequest response text, which consists of an article list retrieved from the database.

Add a text field with text_field_tag method:

<%=text_field_tag:section %>

Specify the text field to observe and the div to update with the observe_field method:

<%= observe_field(:section, :frequency=>
0.1, :update=>
"article_list", :url=>
: get_article_list })%>

The observe_field method specifies that the :section text field is to be observed, with a polling frequency of :frequency seconds. The :update option specifies the div to be updated with XMLHttpRequest response text and :url specifies the controller action that is invoked at the polling frequency.

The index.rhtml view template is available in the Resources zip file.

Processing a Request

In the example application, the observe_field method sends a XMLHttpRequest request to the get_article_list action in the controller. The controller class obtains a data result set using an SQL query created from the section value specified in the view and then outputs a list of retrieved articles. The controller class, CatalogController, runs the SQL query using the model class, Catalog.

Create the model class, Catalog, with the following command:

C:/ruby/railsapp>ruby script/generate model  catalog

By default, a connection is established using the connection parameters in the database.yml file. By default, the table name used is the plural of the model class with the first letter lowercased. The database, table name, or other connection parameters may be set in the catalog.rb file using the establish_connection and set_tabe_name methods.

Modify the catalog.rb Ruby file to create a MySQL database connection. In the Catalog class, set the table name from which data is to be retrieved with the set_table_name method of the ActiveRecord::Base class thusly:

class Catalog < ActiveRecord::Base
set_table_name "catalogs" 

Next, establish a connection with the database with the establish_connection method. For a connection with the MySQL database, specify the :adapter value as “mysql” in lowercase:

   :adapter  => "mysql",
   :host     =>  "localhost",
   :database =>  “test”, 
   :username =>  "root",
   :password =>   

The complete listing for the catalog.rb model class is available in the Resources zip file.

The controller class CatalogController (catalog_controller.rb file) integrates the model with the view. CatalogController consists of actions index and get_article_list. The index action has a corresponding view template in the views/catalog directory.

In the get_article_list method, we retrieve the value of the section text field:


Then we construct a local variable, @catalogList, for a list of articles retrieved for a section:


The ActiveRecord::Base class provides various finder methods to query a database.

We run a SQL query with a SELECT statement using the specified section value and then iterate over the result set to construct a list of articles that match the section value:

Catalog.find_by_sql("SELECT * from catalogs WHERE SECTION='"+@section+"'").each do|catalog|
@catalogList+="<li><a href=\""+catalog.url+"\">" +catalog.title+ "</a></li>"

We return the response to the index.rhtml view with render:text:

render:text=> @catalogList

The controller script, catalog_controller.rb, is available in the Resources zip file.

Processing a Response

The response from the controller class is used to update the article_list div specified in the :update option of the observe_field method. We’ll now run the MVC Ruby on Rails application after first starting the WEBrick web server:

C:/ruby/railsapp>ruby script/server

The web server can be accessed using url http://localhost:3000/ and we can invoke the index action of the Catalog controller with url http://localhost:3000/Catalog/index in a web browser. This displays an input form (Figure 1 Search Form):

Figure 1. Search Form.

We specify a section field value and if the specified section value does not match a section value in the database, an article list is not displayed (Figure 2. Specifying a Section Value.):

Figure 2. Specifying a Section Value.

We chose to specify a section value that matches a section in the database table catalogs, such as ‘XML’, for example. A list of articles that match the specified section is displayed without clicking on a button (Figure 3. Catalog Search Result.):

Figure 3. Catalog Search Result.

A Rails-implemented Ajax application is simpler to develop than an ordinary J2EE Ajax application, so many enterprise organisations are using Ruby on Rails (see “Who is already on Rails?” at the homepage here).

Beginner's guide to SSL certificates

More from The Register

next story
Download alert: Nearly ALL top 100 Android, iOS paid apps hacked
Attack of the Clones? Yeah, but much, much scarier – report
NSA SOURCE CODE LEAK: Information slurp tools to appear online
Now you can run your own intelligence agency
Microsoft: Your Linux Docker containers are now OURS to command
New tool lets admins wrangle Linux apps from Windows
Microsoft adds video offering to Office 365. Oh NOES, you'll need Adobe Flash
Lovely presentations... but not on your Flash-hating mobe
You stupid BRICK! PCs running Avast AV can't handle Windows fixes
Fix issued, fingers pointed, forums in flames
HTML5 vs native: Harry Coder and the mudblood mobile app princes
Developers just want their ideas to generate money
prev story


Designing and building an open ITOA architecture
Learn about a new IT data taxonomy defined by the four data sources of IT visibility: wire, machine, agent, and synthetic data sets.
The total economic impact of Druva inSync
Examining the ROI enterprises may realize by implementing inSync, as they look to improve backup and recovery of endpoint data in a cost-effective manner.
A strategic approach to identity relationship management
ForgeRock commissioned Forrester to evaluate companies’ IAM practices and requirements when it comes to customer-facing scenarios versus employee-facing ones.
Reg Reader Research: SaaS based Email and Office Productivity Tools
Read this Reg reader report which provides advice and guidance for SMBs towards the use of SaaS based email and Office productivity tools.
Business security measures using SSL
Examines the major types of threats to information security that businesses face today and the techniques for mitigating those threats.