views:

433

answers:

3

I'm trying to write a Rails controller method that will respond to get requests made both "normally" (e.g. following a link) and via ajax.

Normal Case: The controller should respond with fully decorated HTML using the layout.

Ajax Case: The conroller should respond with the HTML snippet generated by the template (no layout)

Here's the jQuery code, I've created to run on the client side to do the get request.

jQuery.get("http://mydomain.com/some_controller/some_action", 
           {}, 
           function(data, textstatus) {
             jQuery("#target").html(data);
           },
           "html");

What's the best way to handle this in Rails?

+4  A: 

In your controller dynamically select whether to use a layout based on request.xhr?

e.g.

class SomeController < ApplicationController
  layout :get_layout

  def get_layout
    request.xhr? nil : 'NormalLayout'
  end

end
DanSingerman
+6  A: 

In your controller method, simply do this:

   respond_to do |format|
      format.js if request.xhr?
      format.html { redirect_to :action => "index"}
    end
JRL
Ooh - I didn't know about request.xhr? Hope you don't mind if I edit my answer to use that.
DanSingerman
A: 

If you're using a new version of rails you can just append .js onto the path and it will infer that the request is a JavaScript call

brianthecoder