Flowdock
method

link_to_remote

Importance_5
Ruby on Rails latest stable (v4.0.2) - 4 notes - Class: ActionView::Helpers::PrototypeHelper

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

link_to_remote(name, options = {}, html_options = nil) public

Returns a link to a remote action defined by options[:url] (using the url_for format) that’s called in the background using XMLHttpRequest. The result of that request can then be inserted into a DOM object whose id can be specified with options[:update]. Usually, the result would be a partial prepared by the controller with render :partial.

Examples:

  # Generates: <a href="#" onclick="new Ajax.Updater('posts', '/blog/destroy/3', {asynchronous:true, evalScripts:true});
  #            return false;">Delete this post</a>
  link_to_remote "Delete this post", :update => "posts",
    :url => { :action => "destroy", :id => post.id }

  # Generates: <a href="#" onclick="new Ajax.Updater('emails', '/mail/list_emails', {asynchronous:true, evalScripts:true});
  #            return false;"><img alt="Refresh" src="/images/refresh.png?" /></a>
  link_to_remote(image_tag("refresh"), :update => "emails",
    :url => { :action => "list_emails" })

You can override the generated HTML options by specifying a hash in options[:html].

  link_to_remote "Delete this post", :update => "posts",
    :url  => post_url(@post), :method => :delete,
    :html => { :class  => "destructive" }

You can also specify a hash for options[:update] to allow for easy redirection of output to an other DOM element if a server-side error occurs:

Example:

  # Generates: <a href="#" onclick="new Ajax.Updater({success:'posts',failure:'error'}, '/blog/destroy/5',
  #            {asynchronous:true, evalScripts:true}); return false;">Delete this post</a>
  link_to_remote "Delete this post",
    :url => { :action => "destroy", :id => post.id },
    :update => { :success => "posts", :failure => "error" }

Optionally, you can use the options[:position] parameter to influence how the target DOM element is updated. It must be one of :before, :top, :bottom, or :after.

The method used is by default POST. You can also specify GET or you can simulate PUT or DELETE over POST. All specified with options[:method]

Example:

  # Generates: <a href="#" onclick="new Ajax.Request('/person/4', {asynchronous:true, evalScripts:true, method:'delete'});
  #            return false;">Destroy</a>
  link_to_remote "Destroy", :url => person_url(:id => person), :method => :delete

By default, these remote requests are processed asynchronous during which various JavaScript callbacks can be triggered (for progress indicators and the likes). All callbacks get access to the request object, which holds the underlying XMLHttpRequest.

To access the server response, use request.responseText, to find out the HTTP status, use request.status.

Example:

  # Generates: <a href="#" onclick="new Ajax.Request('/words/undo?n=33', {asynchronous:true, evalScripts:true,
  #            onComplete:function(request){undoRequestCompleted(request)}}); return false;">hello</a>
  word = 'hello'
  link_to_remote word,
    :url => { :action => "undo", :n => word_counter },
    :complete => "undoRequestCompleted(request)"

The callbacks that may be specified are (in order):

:loading:Called when the remote document is being loaded with data by the browser.
:loaded:Called when the browser has finished loading the remote document.
:interactive:Called when the user can interact with the remote document, even though it has not finished loading.
:success:Called when the XMLHttpRequest is completed, and the HTTP status code is in the 2XX range.
:failure:Called when the XMLHttpRequest is completed, and the HTTP status code is not in the 2XX range.
:complete:Called when the XMLHttpRequest is complete (fires after success/failure if they are present).

You can further refine :success and :failure by adding additional callbacks for specific status codes.

Example:

  # Generates: <a href="#" onclick="new Ajax.Request('/testing/action', {asynchronous:true, evalScripts:true,
  #            on404:function(request){alert('Not found...? Wrong URL...?')},
  #            onFailure:function(request){alert('HTTP Error ' + request.status + '!')}}); return false;">hello</a>
  link_to_remote word,
    :url => { :action => "action" },
    404 => "alert('Not found...? Wrong URL...?')",
    :failure => "alert('HTTP Error ' + request.status + '!')"

A status code callback overrides the success/failure handlers if present.

If you for some reason or another need synchronous processing (that’ll block the browser while the request is happening), you can specify options[:type] = :synchronous.

You can customize further browser side call logic by passing in JavaScript code snippets via some optional parameters. In their order of use these are:

:confirm:Adds confirmation dialog.
:condition:Perform remote request conditionally by this expression. Use this to describe browser-side conditions when request should not be initiated.
:before:Called before request is initiated.
:after:Called immediately after request was initiated and before :loading.
:submit:Specifies the DOM element ID that’s used as the parent of the form elements. By default this is the current form, but it could just as well be the ID of a table row or any other DOM element.
:with:A JavaScript expression specifying the parameters for the XMLHttpRequest. Any expressions should return a valid URL query string.

Example:

  :with => "'name=' + $('name').value"

You can generate a link that uses AJAX in the general case, while degrading gracefully to plain link behavior in the absence of JavaScript by setting html_options[:href] to an alternate URL. Note the extra curly braces around the options hash separate it as the second parameter from html_options, the third.

Example:

  link_to_remote "Delete this post",
    { :update => "posts", :url => { :action => "destroy", :id => post.id } },
    :href => url_for(:action => "destroy", :id => post.id)
Show source
Register or log in to add new notes.
July 4, 2008
0 thanks

Add if before Ajax.request

Use link_to_remote’s before

link_to_remote(“watcher”, {:url => “/watchers/add”, :before => “if($F(‘user_id’)==”){return false;}” })

<a onclick=“if($F(‘user_id’)==”){return false;}; new Ajax.Request(‘/watchers/add’, {asynchronous:true, evalScripts:true, parameters:”}); return false;”>添加订阅人

March 31, 2010
0 thanks

Always gracefully degrade if JS isn't available

If you always want to degrade when JS isn’t available you can add something like to environment.rb

module ActionView
  module Helpers
    module PrototypeHelper
      def link_to_remote(name, options = {}, html_options = nil)
         html_options ||= {}
         html_options[:href] ||= options[:url]
         link_to_function(name, remote_function(options), html_options || options.delete(:html))
      end
    end
  end
end