Monday, July 28, 2008

Building interactive web pages using AJAX and RJS

When we talk about interactive web applications, AJAX is one of the most important technologies. Rails provides an easy way to use Ajax in your web site through RJS. RJS helps you make and ajax request and have several page elements updated correspondingly.

Implementing Ajax requests using RJS is a simple matter of doing the following:

  • Include the requried javascript files.
  • Use the right rails tags to launch an ajax request.
  • Declare that your action in the controller can respond to rjs.
  • Define the rjs response (the changes to the DOM).

Any rails application has the javascript files (prototype.js, effects.js, dragdrop.js, controls.js, application.js) by default. All you need to do is to include them in your layout file by adding:

<%= javascript_include_tag :defaults %>

Rails provide 'remote' alternatives for its link and form tags

  • link_to_remote vs link_to
  • form_remote_for vs form_for and
  • form_remote_tag vs form_tag.

Using the remote alternative will cause the html tags generated to have a new AjaxRequest call;
so when u specify:

<%= link_to_remote "Some text", :url => {:action=>'action_name'}%>

This will cause the new anchor tag to have an onsubmit attribute with the required ajax call to the action.

You need also to declare that the controller method responds to ajax by adding the following part to it. (You can also add format.html of action can be called with a normal request)

respond_to do |format|
    format.js
end

Finally, define the changes in the DOM (reponse) in the a new .rjs file in the views directory

page.replace_html :element_id, 'new html replacement'
page.insert_html :bottom, :element_id2, 'new html element below the element_id2 element'
page.insert_html :top, :element_id3, :partial => 'partial_name' , :object=> @object

Ryan Bates provided a nice demonstration on how to make Ajax calls with rjs in his rails casts.

No comments: