module ActionView::Helpers::JqueryHelper

Constants

AJAX_OPTIONS
JQCALLBACKS
JQUERY_VAR
USE_PROTECTION

Public Instance Methods

button_to_remote(name, options = {}, html_options = {}) click to toggle source

Creates a button with an onclick event which calls a remote action via XMLHttpRequest The options for specifying the target with :url and defining callbacks is the same as link_to_remote.

# File lib/action_view/helpers/jquery_helper.rb, line 78
def button_to_remote(name, options = {}, html_options = {})
  button_to_function(name, remote_function(options), html_options)
end
evaluate_remote_response() click to toggle source

Returns ‘eval(request.responseText)’ which is the JavaScript function that form_remote_tag can call in :complete to evaluate a multiple update return document using update_element_function calls.

# File lib/action_view/helpers/jquery_helper.rb, line 358
def evaluate_remote_response
  "#{JQUERY_VAR}.globalEval(request.responseText)"
end
form_remote_for(record, options = {})
Alias for: remote_form_for
form_remote_tag(options = {}, &block) click to toggle source

Returns a form tag that will submit using XMLHttpRequest in the background instead of the regular reloading POST arrangement. Even though it’s using JavaScript to serialize the form elements, the form submission will work just like a regular submission as viewed by the receiving side (all elements available in params). The options for specifying the target with :url and defining callbacks is the same as link_to_remote.

A “fall-through” target for browsers that doesn’t do JavaScript can be specified with the :action/:method options on :html.

Example:

# Generates:
#      <form action="/some/place" method="post" onsubmit="new Ajax.Request('',
#      {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
form_remote_tag :html => { :action =>
  url_for(:controller => "some", :action => "place") }

The Hash passed to the :html key is equivalent to the options (2nd) argument in the FormTagHelper.form_tag method.

By default the fall-through action is the same as the one specified in the :url (and the default method is :post).

form_remote_tag also takes a block, like form_tag:

# Generates:
#     <form action="/" method="post" onsubmit="new Ajax.Request('/',
#     {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)});
#     return false;"> <div><input name="commit" type="submit" value="Save" /></div>
#     </form>
<% form_remote_tag :url => '/posts' do -%>
  <div><%= submit_tag 'Save' %></div>
<% end -%>
# File lib/action_view/helpers/jquery_helper.rb, line 286
def form_remote_tag(options = {}, &block)
  options[:form] = true

  options[:html] ||= {}
  options[:html][:onsubmit] =
    (options[:html][:onsubmit] ? options[:html][:onsubmit] + "; " : "") +
    "#{remote_function(options)}; return false;"

  form_tag(options[:html].delete(:action) || url_for(options[:url]), options[:html], &block)
end
method_option_to_s(method) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 470
def method_option_to_s method
  (method.is_a?(String) and !method.index("'").nil?) ? method : "'#{method}'"
end
observe_field(field_id, options = {}) click to toggle source

Observes the field with the DOM ID specified by field_id and calls a callback when its contents have changed. The default callback is an Ajax call. By default the value of the observed field is sent as a parameter with the Ajax call.

Example:

# Generates: new Form.Element.Observer('suggest', 0.25, function(element, value) {new Ajax.Updater('suggest',
#         '/testing/find_suggestion', {asynchronous:true, evalScripts:true, parameters:'q=' + value})})
<%= observe_field :suggest, :url => { :action => :find_suggestion },
     :frequency => 0.25,
     :update => :suggest,
     :with => 'q'
     %>

Required options are either of:

:url

url_for-style options for the action to call when the field has changed.

:function

Instead of making a remote call to a URL, you can specify javascript code to be called instead. Note that the value of this option is used as the body of the javascript function, a function definition with parameters named element and value will be generated for you for example:

observe_field("glass", :frequency => 1, :function => "alert('Element changed')")

will generate:

new Form.Element.Observer('glass', 1, function(element, value) {alert('Element changed')})

The element parameter is the DOM element being observed, and the value is its value at the time the observer is triggered.

Additional options are:

:frequency

The frequency (in seconds) at which changes to this field will be detected. Not setting this option at all or to a value equal to or less than zero will use event based observation instead of time based observation.

:update

Specifies the DOM ID of the element whose innerHTML should be updated with the XMLHttpRequest response text.

:with

A JavaScript expression specifying the parameters for the XMLHttpRequest. The default is to send the key and value of the observed field. Any custom expressions should return a valid URL query string. The value of the field is stored in the JavaScript variable value.

Examples

:with => "'my_custom_key=' + value"
:with => "'person[name]=' + prompt('New name')"
:with => "Form.Element.serialize('other-field')"

Finally

:with => 'name'

is shorthand for

:with => "'name=' + value"

This essentially just changes the key of the parameter.

Additionally, you may specify any of the options documented in the Common options section at the top of this document.

Example:

# Sends params: {:title => 'Title of the book'} when the book_title input
# field is changed.
observe_field 'book_title',
  :url => 'http://example.com/books/edit/1',
  :with => 'title'
# File lib/action_view/helpers/jquery_helper.rb, line 431
def observe_field(field_id, options = {})
  build_observer(field_id, options)
end
observe_form(form_id, options = {}) click to toggle source

Observes the form with the DOM ID specified by form_id and calls a callback when its contents have changed. The default callback is an Ajax call. By default all fields of the observed field are sent as parameters with the Ajax call.

The options for observe_form are the same as the options for observe_field. The JavaScript variable value available to the :with option is set to the serialized form by default.

# File lib/action_view/helpers/jquery_helper.rb, line 443
def observe_form(form_id, options = {})
  build_observer(form_id, options)
end
periodically_call_remote(options = {}) click to toggle source

Periodically calls the specified url (options[:url]) every options[:frequency] seconds (default is 10). Usually used to update a specified div (options[:update]) with the results of the remote call. The options for specifying the target with :url and defining callbacks is the same as link_to_remote. Examples:

# Call get_averages and put its results in 'avg' every 10 seconds
# Generates:
#      new PeriodicalExecuter(function() {new Ajax.Updater('avg', '/grades/get_averages',
#      {asynchronous:true, evalScripts:true})}, 10)
periodically_call_remote(:url => { :action => 'get_averages' }, :update => 'avg')

# Call invoice every 10 seconds with the id of the customer
# If it succeeds, update the invoice DIV; if it fails, update the error DIV
# Generates:
#      new PeriodicalExecuter(function() {new Ajax.Updater({success:'invoice',failure:'error'},
#      '/testing/invoice/16', {asynchronous:true, evalScripts:true})}, 10)
periodically_call_remote(:url => { :action => 'invoice', :id => customer.id },
   :update => { :success => "invoice", :failure => "error" }

# Call update every 20 seconds and update the new_block DIV
# Generates:
# new PeriodicalExecuter(function() {new Ajax.Updater('news_block', 'update', {asynchronous:true, evalScripts:true})}, 20)
periodically_call_remote(:url => 'update', :frequency => '20', :update => 'news_block')
# File lib/action_view/helpers/jquery_helper.rb, line 46
def periodically_call_remote(options = {})
  frequency = options[:frequency] || 10 # every ten seconds by default
  code = "setInterval(function() {#{remote_function(options)}}, #{frequency} * 1000)"
  javascript_tag(code)
end
remote_form_for(record, options = {}) click to toggle source

Creates a form that will submit using XMLHttpRequest in the background instead of the regular reloading POST arrangement and a scope around a specific resource that is used as a base for questioning about values for the fields.

Resource

Example:

<% remote_form_for(@post) do |f| %>
  ...
<% end %>

This will expand to be the same as:

<% remote_form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
  ...
<% end %>

Nested Resource

Example:

<% remote_form_for([@post, @comment]) do |f| %>
  ...
<% end %>

This will expand to be the same as:

<% remote_form_for :comment, @comment, :url => post_comment_path(@post, @comment), :html => { :method => :put, :class => "edit_comment", :id => "edit_comment_45" } do |f| %>
  ...
<% end %>

If you don’t need to attach a form to a resource, then check out form_remote_tag.

See FormHelper#form_for for additional semantics.

# File lib/action_view/helpers/jquery_helper.rb, line 331
def remote_form_for record, options = {}, &block
  as = options[:as]

  case record
  when String, Symbol
    object_name = record
    object = nil
  else
    object = if record.is_a? Array then record.last else record end
    if Rails::VERSION::MAJOR >= 4
      object_name = as || model_name_from_record_or_class(object).param_key
      apply_form_for_options! record, object, options
    else
      object_name = as || ActiveModel::Naming.param_key(object)
      apply_form_for_options! record, options
    end
  end

  form_remote_tag options do
    fields_for object, options, &block
  end
end
Also aliased as: form_remote_for
remote_function(options) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 52
def remote_function(options)
  javascript_options = options_for_ajax(options)

  update = ''
  if options[:update] && options[:update].is_a?(Hash)
    update  = []
    update << "success:'#{options[:update][:success]}'" if options[:update][:success]
    update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure]
    update  = '{' + update.join(',') + '}'
  elsif options[:update]
    update << "'#{options[:update]}'"
  end

  function = "#{JQUERY_VAR}.ajax(#{javascript_options})"

  function = "#{options[:before]}; #{function}" if options[:before]
  function = "#{function}; #{options[:after]}"  if options[:after]
  function = "if (#{options[:condition]}) { #{function}; }" if options[:condition]
  function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm]
  return function
end
submit_to_remote(name, value, options = {}) click to toggle source

Returns a button input tag with the element name of name and a value (i.e., display text) of value that will submit form using XMLHttpRequest in the background instead of a regular POST request that reloads the page.

# Create a button that submits to the create action
#
# Generates: <input name="create_btn" onclick="new Ajax.Request('/testing/create',
#     {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)});
#     return false;" type="button" value="Create" />
<%= submit_to_remote 'create_btn', 'Create', :url => { :action => 'create' } %>

# Submit to the remote action update and update the DIV succeed or fail based
# on the success or failure of the request
#
# Generates: <input name="update_btn" onclick="new Ajax.Updater({success:'succeed',failure:'fail'},
#      '/testing/update', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)});
#      return false;" type="button" value="Update" />
<%= submit_to_remote 'update_btn', 'Update', :url => { :action => 'update' },
   :update => { :success => "succeed", :failure => "fail" }

options argument is the same as in form_remote_tag.

# File lib/action_view/helpers/jquery_helper.rb, line 103
def submit_to_remote(name, value, options = {})
  options[:with] ||= "#{JQUERY_VAR}(this.form).serialize()"

  html_options = options.delete(:html) || {}
  html_options[:name] = name

  button_to_remote(value, options, html_options)
end
update_page(&block) click to toggle source

Yields a JavaScriptGenerator and returns the generated JavaScript code. Use this to update multiple elements on a page in an Ajax response. See JavaScriptGenerator for more information.

Example:

update_page do |page|
  page.hide 'spinner'
end
# File lib/action_view/helpers/jquery_helper.rb, line 456
def update_page(&block)
  JavaScriptGenerator.new(self, &block).to_s.html_safe
end
update_page_tag(html_options = {}, &block) click to toggle source

Works like update_page but wraps the generated JavaScript in a <script> tag. Use this to include generated JavaScript in an ERb template. See JavaScriptGenerator for more information.

html_options may be a hash of <script> attributes to be passed to ActionView::Helpers::JavaScriptHelper#javascript_tag.

# File lib/action_view/helpers/jquery_helper.rb, line 466
def update_page_tag(html_options = {}, &block)
  javascript_tag update_page(&block), html_options
end

Protected Instance Methods

build_callbacks(options) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 560
def build_callbacks(options)
  callbacks = {}
  options[:beforeSend] = '';
  [:uninitialized,:loading].each do |key|
    options[:beforeSend] << (options[key].last == ';' ? options.delete(key) : options.delete(key) << ';') if options[key]
  end
  options.delete(:beforeSend) if options[:beforeSend].blank?
  options[:complete] = options.delete(:loaded) if options[:loaded]
  options[:error] = options.delete(:failure) if options[:failure]
  if options[:update]
    if options[:update].is_a?(Hash)
      options[:update][:error] = options[:update].delete(:failure) if options[:update][:failure]
      if options[:update][:success]
        options[:success] = build_update_for_success(options[:update][:success], options[:position]) << (options[:success] ? options[:success] : '')
      end
      if options[:update][:error]
        options[:error] = build_update_for_error(options[:update][:error], options[:position]) << (options[:error] ? options[:error] : '')
      end
    else
      options[:success] = build_update_for_success(options[:update], options[:position]) << (options[:success] ? options[:success] : '')
    end
  end
  options.each do |callback, code|
    if JQCALLBACKS.include?(callback)
      callbacks[callback] = "function(request){#{code}}"
    end
  end
  callbacks
end
build_insertion(insertion) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 536
def build_insertion(insertion)
  insertion = insertion ? insertion.to_s.downcase : 'html'
  insertion = 'append' if insertion == 'bottom'
  insertion = 'prepend' if insertion == 'top'
  insertion
end
build_observer(name, options = {}) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 543
def build_observer(name, options = {})
  if options[:with] && (options[:with] !~ /[\{=(.]/)
    options[:with] = "'#{options[:with]}=' + value"
  else
    options[:with] ||= 'value' unless options[:function]
  end

  callback = options[:function] || remote_function(options)
  javascript  = "#{JQUERY_VAR}('#{jquery_id(name)}').delayedObserver("
  javascript << "#{options[:frequency] || 0}, "
  javascript << "function(element, value) {"
  javascript << "#{callback}}"
  #javascript << ", '#{options[:on]}'" if options[:on]
  javascript << ")"
  javascript_tag(javascript)
end
build_update_for_error(html_id, insertion=nil) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 531
def build_update_for_error(html_id, insertion=nil)
  insertion = build_insertion(insertion)
  "#{JQUERY_VAR}('#{jquery_id(html_id)}').#{insertion}(request.responseText);"
end
build_update_for_success(html_id, insertion=nil) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 526
def build_update_for_success(html_id, insertion=nil)
  insertion = build_insertion(insertion)
  "#{JQUERY_VAR}('#{jquery_id(html_id)}').#{insertion}(request);"
end
options_for_ajax(options) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 483
def options_for_ajax(options)
  js_options = build_callbacks(options)

  url_options = options[:url]
  url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash)
  js_options['url'] = "'#{url_for(url_options)}'"
  js_options['async'] = false if options[:type] == :synchronous
  js_options['type'] = options[:method] ? method_option_to_s(options[:method]) : ( options[:form] ? "'post'" : nil )
  js_options['dataType'] = options[:datatype] ? "'#{options[:datatype]}'" : (options[:update] ? "'html'" : "'script'")

  if options[:form]
    js_options['data'] = "#{JQUERY_VAR}.param(#{JQUERY_VAR}(this).serializeArray())"
  elsif options[:submit]
    js_options['data'] = "#{JQUERY_VAR}(\"##{options[:submit]}:input\").serialize()"
  elsif options[:with]
    js_options['data'] = options[:with].gsub("Form.serialize(this.form)","#{JQUERY_VAR}.param(#{JQUERY_VAR}(this.form).serializeArray())")
  end

  js_options['type'] ||= "'post'"
  if options[:method]
    if method_option_to_s(options[:method]) == "'put'" || method_option_to_s(options[:method]) == "'delete'"
      js_options['type'] = "'post'"
      if js_options['data']
        js_options['data'] << " + '&"
      else
        js_options['data'] = "'"
      end
      js_options['data'] << "_method=#{options[:method]}'"
    end
  end

  if USE_PROTECTION && respond_to?('protect_against_forgery?') && protect_against_forgery?
    if js_options['data']
      js_options['data'] << " + '&"
    else
      js_options['data'] = "'"
    end
    js_options['data'] << "#{request_forgery_protection_token}=' + encodeURIComponent('#{escape_javascript form_authenticity_token}')"
  end
  js_options['data'] = "''" if js_options['type'] == "'post'" && js_options['data'].nil?
  options_for_javascript(js_options.reject {|key, value| value.nil?})
end
options_for_javascript(options) click to toggle source
# File lib/action_view/helpers/jquery_helper.rb, line 475
def options_for_javascript(options)
  if options.empty?
    '{}'
  else
    "{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}"
  end
end