Friday, March 9, 2012

Simple Ajax Update in Rails 3

There have been several updates to the way Rails 3 interacts with Ajax.

One big change was the switch from prototype to Jquery as the standard Javascript library. Having spent a short time with Jquery, I can see how it is much more elegant and easier to understand, at least superficially. I am not a Javascript expert, but I've done a fair bit of "raw" coding accessing and manipulating the DOM, enough to appreciate the power of Jquery.

Here are the minimal code snippets to update an element in a web page with an Ajax call using the new syntax.

In the view:
<%= link_to "test", { :action => 'testajax' }, :remote => true %>
<div id='testdiv'></div>

The :remote => true indicates an Ajax link.  We are going to update the div testdiv.

In the controller, define a function to handle the call:
def testajax
  @testdata = "ajaxy data"
end


Create a new view file for the javascript response (in this case named testajax.js.erb):
$("#testdiv").html("<%= @testdata %>");

This is Jquery Javascript code, but you can use embedded ruby to pull in instance variables from the controller.  We are selecting the html content of the element with ID testdiv, then updating it with the data set in the controller "ajaxy data".


7 comments:

  1. Great post. Do you have to make the rails 3 routes.rb to make testajax a viable route?

    ReplyDelete
  2. Rich,

    In Rails 3, I always add new methods to routes.rb so Rails knows specifically where to locate it. However, it might work without a routes.rb entry if the method is in the same controller associated with the view. I'm not sure without running a test.

    ReplyDelete
  3. It worked just fine when I re-used the index method as the action and had the index method generate @testdata.

    When I tried setting the action, as you did, to testajax, and adding a route for that:

    get '/home/testajax', to: 'home#testajax'

    I kept getting:

    Missing template home/testajax, application/testajax

    After trying to add a variety of probably incorrect templates it felt like a rathole.

    Is there something you do to tell Rails NOT to look for a template?


    ReplyDelete
  4. You know what? That route started working for me when I removed some cruft from my routes.rb!

    Thanks again. This got me started with AJAX. I really appreciate posts that have the minimum_required_code_plus_explanations. Great job.

    ReplyDelete
  5. Rich,

    Glad you got it working. Rails will always look for a template when rendering something, whether the template is .erb, .haml, .js, etc. I try to document things that are not obvious to me so I can come back and reference them later, too!

    ReplyDelete
  6. It really helped me. Thank you so much for this update as I finally managed to solve my problem with this :) Thanks!

    ReplyDelete