AJAX in Rails application with RJS
RJS - Ruby JavaScript - Generates and executes javascript code from your controller in AJAX request to process your Ruby code as well as updates your page's html DOM finally. To see details of how it works lets start
1. Suppose you have an ajax request call with an anchor tag in your view file like:
<%= link_to_remote('Click Me to show RJS',{:url => {:controller => 'experiment', :action => 'rjs'}, :loading => "", :complete => ''},{}) %>
this is content
And you want to update div of id 'id1' then
2. In Controller :
def rjs
#you may have ROR stuff here
render :update do |page|
page.replace_html 'id1', 'This is content after AJAX call' # div with id1 will be replaced with the string
end
end
Now click on the anchor then div of id ‘id1’ will be replaced by controller’s action’s method rjs’s response
Thats all of RJS basic with only 2 steps
Now if you want to replace div of id1 with another file’s content then you can do it like:
page.replace_html 'id1', :partial => "experiment/parts/part1", :locals => {:p1 => 1, :p2 => 2}
# part1 is your partial file (located in views/experiment/parts/_part1.html.erb)
# And you may pass parameters with locals p1, p2, …. pn
# you can catch this params in _part1.html.erb file like : <%= p1 %>
# You can also update more than 1 div in your view file with the same ajax request like:
page.replace_html 'id1', :partial => "experiment/parts/part1"
page.replace_html 'id2', ‘Another String’
page.remove ‘remove_div_id’
page << “js_mehtod()” # where js_mehtod() is the javascript function which resides in your view.
Now AJAX call with form submit event
this is content
<% form_remote_tag :url => {:controller => 'experiment', :action => 'rjs'}, :loading => '', :complete => '', :html => {:method => :post} do %>
<%= text_field :name %>
<%= submit_tag(Submit) %>
<% end %>
To know more visit: http://www.developer.com/lang/print.php/10924_3668331_2