http://www.developer.com/

Back to article

RJS Templates: Adding Some Ajax Goodness to Rails


March 28, 2007

Ruby on Rails is a powerful web application framework that provides numerous tools for creating web applications fast! It is a full-stack framework for developing database-backed web applications according to the Model-View-Control pattern. Rails also provides Ajax support in the view layer, a request and response controller, and a domain model wrapping the database. Ajax is a creative technique used to make web sites more interactive and responsive to user input. RJS templates are an exciting and powerful new type of template added to Rails 1.1. This article will introduce RJS templates and show how they allow you to easily add Ajax functionality to your web application.

Ajax

Ajax is an acronym for "Asynchronous JavaScript and XML". It is a web application programming technique used to create more interactive web applications. Initially created by Jesse James Garrett of Adaptive Path, Ajax uses JavaScript and the built in XMLHttpRequest object found in web browsers (Internet Explorer, Mozilla, and Firefox to name a few) to manipulate the DOM object representation of a web page, all without a page refresh. This is a very powerful technique because it saves time and provides a more responsive experience to the user.

Rails RJS Templates

Conventional Rails templates can generate HTML (.rhtml extension files) or XML (.rxml extension files). RJS templates (.rjs extension files) generate JavaScript code that is executed when it is returned to the browser. The JavaScript code generated allows you to perform multiple page updates, without a page refresh, using Ajax. These RJS templates, written in Ruby, are all you need to generate this JavaScript code and allow for some cool Ajax functionality to your Rails application.

Getting Started

You can create a simple Rails application and add RJS support to it. To begin, you need to create a rails app 'rsjtest' by issuing the command 'rails rjstest':



Click here for a larger image.

This creates an 'rjstest' directory containing your initial web application:



Click here for a larger image.

Creating the Web Page You Will Use to Test the RSJ Template

Within the rails application, the models, views, and controllers of the application live in the 'app' directory. Your intention is to create a simple web page that you can test out a sample RJS template. So, begin by creating the page that will you will use to test the RJS Template functionality. Create a file 'index.rhtml' in the 'app/views/rjs' directory. This will be the default page Rails will serve up to the browser when a URL of 'http://localhost:3000/rjs/' is requested from your web browser. Edit the 'index.rhtml' file and add the following:

<html>

<head>

<title>RJS Template Test</title>

</head>

<body>
   <h1>RJS Template Test</h1>


   <%= javascript_include_tag :defaults %>


   <%= link_to_remote("Test out RJS!",
       :url =>{ :controller => "rjs", :action => "hello" }) %>
</body>
</html>

The HTML should be familiar, but the rails method calls within the <%= and %> tags need some explanation. The javascript_include_tag directive is a built-in Rails method that tells the layout to use the Rails JavaScript libraries. The link_to_remote method is actually a helper method available in the Rails ActionView::Helpers::PrototypeHelper module. This module provides a set of helpers for calling Prototype JavaScript functions, including functionality to call remote methods using Ajax. It returns a link to a remote action defined by the 'url' parameter. The remote action is called in the background using XMLHttpRequest. The result of that request then can be inserted into a DOM object whose ID can be specified via the 'update' parameter. Your specific method call tells Rails to use Ajax to invoke the 'hello' action of your 'rjs' controller. You do not specify any 'update' parameter because you are not updating the DOM in this example.

Creating the Controller and View

Generate a Controller and View for your test. This controller will be the one defining the action defined in your 'link_to_remote' call specified in the RHTML file. You will be using a controller names 'rjs'. Issue the commands below to create the Controller and View:



Click here for a larger image.

You should now have an 'rjs_controller.rb' file in the 'app/controllers' directory and a 'views/rjs' directory. Edit the 'rjs_controller.rb' file and add an empty 'hello' method:

class RjsController < ApplicationController

def hello

end

end

This method is empty because you are not passing anything on to the view, but are allowing your RJS Template to do its magic.

Creating the RSJ Template

To create your RJS template, you need to create a file named 'hello.rjs' in the 'appsviewsrjs' directory. Edit the file to look like the following:

page.alert "Hello from RJS!"

This will use the JavaScript alert method to print the message "Hello from RJS!". You, however, can add any JavaScript commands or an RJS file.

Testing RSJ

Start your 'rjstest' application and point your browser to 'http://localhost:3000/rjs/'. You will see the following:

Click on the 'Test out RJS' link and you will see the following:

Your 'hello.rjs' RJS template was invoked via the 'hello' action of the 'rjs' controller and printe the alert message. Simple, isn't it?

Updating the DOM with RJS

Now, use RJS to update the DOM of the RHTML page. Modify the 'index.rhtml' file to look like this:

<html>

<head>

<title>RJS Template Test</title>

</head>

<body>
   <h1>RJS Template Test</h1>


   <%= javascript_include_tag :defaults %>

   <div id="rjs">I will be updated.</div>

   <%= link_to_remote("Test out RJS!",
       :url =>{ :controller => "rjs", :action => "hello" }) %>

</body>

</html>

Notice that you added a div containing some text. Update the 'hello.rjs' file to look like this:

page.replace_html "rjs", "<b>See!</b>"

Now, start your 'rjstest' application and point your browser to 'http://localhost:3000/rjs/'. You will see the following:

Click on the 'Test out RJS' link and you will see the following:

You have updated DOM for the page, which changed the "I will be updated" text to "See!" in bold.

Conclusion

This fourth article in my Ruby on Rails series has shown you how to use the RJS Template feature of Rails to add Ajax functionality to your Rails application. Ajax and Rails together are a powerful combination, and can not only enhance the user experience of your Rails application, but also increase performance because fewer page reloads are necessary to perform tasks. With Ajax and Rails, you are well on your way to joining the Web 2.0 world.

References

About the Author

Dominic Da Silva (http://www.dominicdasilva.com/) is the President of SilvaSoft, Inc., a software consulting company specializing in Java-, Ruby-, and .NET-based web and web services development. He has worked with Java since the year 2000 and is a Linux user from the 1.0 days. He is also Sun Certified for the Java 2 platform. Born on the beautiful Caribbean island of Trinidad and Tobago, he now makes his home in sunny Orlando, Florida.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date