RJS Templates: Adding Some Ajax Goodness to Rails, Page 2
Start your 'rjstest' application and point your browser to 'http://localhost:3000/rjs/'. 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:
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.
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.
- Ruby: http://www.ruby-lang.org/en/
- Ruby on Rails: http://www.rubyonrails.org/
- An Interview with David Heinemeier Hansson: http://www.oreillynet.com/pub/a/network/2005/08/30/ruby-rails-david-heinemeier-hansson.html
- RubyGems: http://rubygems.rubyforge.org/
- Ajax: http://en.wikipedia.org/wiki/AJAX
- Ajax - A New Approach to Web Applications: http://www.adaptivepath.com/publications/essays/archives/000385.php
- RJS Templates for Rails: http://oreilly.com/catalog/rjsrails/
- SilvaSoft, Inc. weblog: http://jroller.com/page/silvasoftinc
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.
Page 2 of 2