link_to and remote => true + jquery : How? Help?

It is actually quite easy, it just feels like a big deal because it is new. Basically, with the new unobtrusive javascript support, the rails ujs script exposes a set of events you can bind javascript functions to, they are:

  1. ajax:beforeSend – fired before the send occurs
  2. ajax:success – fired after the send occurs, contains the response
  3. ajax:complete – fired after the success event
  4. ajax:error – fired when errors are present

all you need to do is write a function (which you wrap in $document.ready) that in turns binds some anonymous functions to each of these events, or just the events you are interest in.

For example, suppose you have a div that you want to put the response data in with an id of “response_data”, and you have a link with an id of “ajax_trigger”. Something like this:

<%= link_to "My Link", some_model_path(@model_instance), 
                       :remote => true, :html => {:id => "ajax_trigger"} %>
<div id="response_data">
</div>

All you need to do is provide a function like the one below in order to put the response from the server into the div:

$(document).ready(
     function(){
          $("a#ajax_trigger").bind("ajax:success",
                   function(evt, data, status, xhr){
                        //this assumes the action returns an HTML snippet
                        $("div#response_data").html(data);
           }).bind("ajax:error", function(evt, data, status, xhr){
                    //do something with the error here
                    $("div#errors p").text(data);
           });
});

Really, all you are doing with the javascript is handling the response when it comes back from the server. You don’t really have to do anything special to initiate the XHR request, and you can also safely store this method away in .js file that gets served up as a static asset. If you are using Rails 3.1, then you should put it in the appropriately named javascript file that corresponds to the controller. In your controller you need to make sure that you specify :layout => false in the responds_with() method, that way the controller just returns the partial or template it renders, rather than a complete page. This setup also works with actions that return javascript to be executed by the client as well as JSON, depending on what data-type you specify on the request.

I found this blog post to be quite helpful:
http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

Leave a Comment