Ruby on Rails[c] Up and Running
5.7. Ajax
Be sure to include the JavaScript libraries in the layout: <%= javascript_include_tag :defaults %>
5.7.1. Linking to Remote Action
<%= link_to_remote "link", :update => 'some_div', :url => { :action => 'show', :id => post.id } %> <%= link_to_remote "link", :url => { :action => 'create', :update => { :success => 'good_div', :failure => 'error_div' }, :loading => 'Element.show('spinner'), :complete => 'Element.hide('spinner') } %>
5.7.2. Callbacks
You can also specify reactions to return codes directly: link_to_remote word, :url => { :action => "action" }, 404 => "alert('Not found...? Wrong URL...?')", :failure => "alert('HTTP Error ' + request.status + '!')"
5.7.3. Ajax Forms
You can create a form that will submit via an XMLHttpRequest instead of a POST request. The parameters are passed exactly the same way (so the controller can use the params method to access the parameters). Fallback for non-JavaScript-enabled browsers can be specified by using the :action methods in the :html option: form_remote_tag :html => { :action => url_for(:controller => 'controller', :action => 'action'), :method => :post }
5.7.4. Autocompleting Text Field
In the view t\emplate: <%= text_field_with_auto_complete :model, :attribute %>
In the controller: auto_complete_for :model, :attribute
5.7.5. Observe Field
<label for="search">Search term:</label> <%= text_field_tag :search %> <%= observe_field(:search, :frequency => 0.5, :update => :results, :url => { :action => :search }) %> <div id="results"></div>
Optionally specify: :on => :blur # trigger for event (default :changed or :clicked) :with => ... # a JavaScript expression to specify what value is sent # defaults to "value" :with => 'bla' # "'bla' = value" :with => 'a=b' # "a=b"
5.7.6. Observe Form
Same semantics as observe_field . 5.7.7. periodically_call_remote
<%= periodically_call_remote(:update => 'process-list', :url => { :action => :ps }, :frequency => 2 ) %>
Learn more: http://api.rubyonrails.com/classes/ActionView/Helpers/JavaScriptHelper.html. |