AJAX in Ruby-on-Rails
Ruby on Rails and AJAX AJAX can be done with just Javascript Easier if you use libraries –Prototype –SAJAX –jQuery Libraries only handle the client side Ruby on Rails also makes it easy on the server side
Simple Consistent Model A trigger action occurs –button or link, javascript event Data is sent asynchronously Server side action handler takes some action and returns data –may be HTML partial Client side receives the data/HTML and updates the view
Client Side Based on the prototype library Simple Ruby functions –link_to_remote –form_remote_tag –periodically_call_remote –submit_to_remote –remote_function View uses these functions which generate appropriate HTML tags and javascript function calls
View Ajax Demo What time is it? I don't have the time, but <%= link_to_remote( "click here", :update => "time_div", :url =>{ :action => :say_when }) %> and I will look it up.
Details javascript_include_tag –includes the appropriate javascript libraries –:defaults includes a few may also just include specific libraries link_to_remote (can be complex) –most often need text for link name id of the DOM element to update url –may also specify :method - default is POST :position - must be one of :before, :top, :bottom, :after :complete, :success, :failure –javascript callback functions
Server Side AJAX calls are treated just like any other HTTP request However, we don’t want full response layout, css, etc. To suppress full response use –render(:text => “string”) may also use render_text –render(:layout => false) –.js.rjs file with partial –controller with no layout
Example class DemoController < ApplicationController def index end def say_when render_text " The time is " + DateTime.now.to_s + " ” end In this case, there is no view connected to the action method
form_remote_tag { :action => :add_to_cart, :id => product } do -%>
More complex {:controller => "Ajax", :action => "logout" }, :update => 'loginmessage', :complete => remote_function( :url => {:controller => "Ajax", :action => "menu"}, :update => 'sidemenu', :complete => remote_function( :url => {:controller => "Main", :action => "index"} )
.js.rjs templates Controller action methods are paired by name with view files –in app/views/controller_name directory Typically,.html.erb files May also be.js.rjs –ruby javascript –javascript to be executed on load –allows for multiple page updates –written in Ruby Paired with controller action method that doesn’t contain calls to render
.js.rjs example <%= link_to_remote("Test out RJS!", :url =>{ :controller => "shop", :action => "hello" }) %> def hello end page.alert "Hello from RJS!" view code controller code hello.js.rjs - goes into app/views/shop
Updating the DOM with.js.rjs Mark the location to be updated – or Now replace the stuff in that location using page.replace_html –page.replace_html “someid”, “ HI ”.js.rjs file is interpreted into javascript and the javascript is executed when it is loaded
Other page methods alert(message) replace_html(id, *options_for_render) –options for render may be string with html insert_html(position, id, *options_for_render) –position must be :before, :after, :top, :bottom show( *ids ), hide( *ids ), & toggle( *ids ) –toggles the visibility of the html elements visual_effect(effectname, id, options) –page.visual_effect(:fade, ‘someid’, :duration => 0.5) –page.visual_effect(:appear, ‘someid’, :duration => 0.5) –page.visual_effect(:highlight, ‘someid’, :duration => 1)
.js.rjs Much of what you can do is based on the scriptaculous library – Also look at the Ruby on Rails api –ActionView::Helpers::ScriptaculousHelper –ActionView::Helpers::PrototypeHelper
Another Example - View Dynamically populate form elements "sel_con",:url => { :action => :create_select }, :position => "top", :success => "$('sel_con').innerHTML=''" ) do -%> Please select a sports category: <%= select_tag "categories", " Team Individual " %>
Another Example cont - controller def create_select indArr=["Nordic Skiing", "Inline Skating","Tennis", "Triathlon","Road Racing","Figure Skating", "Weight Lifting","Speed Skating","Snowboarding"]; teamArr=["Soccer","Basketball","Football","Hockey", "Baseball","Lacrosse"]; str=""; if (params[:categories].index('Team') != nil) render :partial => "options", :locals => { :sports => teamArr,:sptype => "team"} elsif (params[:categories].index('Individual') != nil) render :partial => "options", :locals => { :sports => indArr, :sptype => "individual" } else str=" unknown "; render :text => str; end
Another Example cont - partial _options " name=" ">