Feeds

Ajax on Rails

Bringing together Ajax and Rails with Prototype

Providing a secure and efficient Helpdesk

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=>
{:action=>
: 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" 
end

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:

ActiveRecord::Base.establish_connection(
   :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:

@section=request.raw_post

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

@catalogList="<ol>"

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

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

Choosing a cloud hosting partner with confidence

More from The Register

next story
Microsoft on the Threshold of a new name for Windows next week
Rebranded OS reportedly set to be flung open by Redmond
Business is back, baby! Hasta la VISTA, Win 8... Oh, yeah, Windows 9
Forget touchscreen millennials, Microsoft goes for mouse crowd
SMASH the Bash bug! Apple and Red Hat scramble for patch batches
'Applying multiple security updates is extremely difficult'
Apple: SO sorry for the iOS 8.0.1 UPDATE BUNGLE HORROR
Apple kills 'upgrade'. Hey, Microsoft. You sure you want to be like these guys?
ARM gives Internet of Things a piece of its mind – the Cortex-M7
32-bit core packs some DSP for VIP IoT CPU LOL
Lotus Notes inventor Ozzie invents app to talk to people on your phone
Imagine that. Startup floats with voice collab app for Win iPhone
'Google is NOT the gatekeeper to the web, as some claim'
Plus: 'Pretty sure iOS 8.0.2 will just turn the iPhone into a fax machine'
prev story

Whitepapers

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.
Storage capacity and performance optimization at Mizuno USA
Mizuno USA turn to Tegile storage technology to solve both their SAN and backup issues.
High Performance for All
While HPC is not new, it has traditionally been seen as a specialist area – is it now geared up to meet more mainstream requirements?
Beginner's guide to SSL certificates
De-mystify the technology involved and give you the information you need to make the best decision when considering your online security options.
Security for virtualized datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.