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?
In your controller dynamically select whether to use a layout based on request.xhr?
.
For example:
class SomeController < ApplicationController
layout :get_layout
protected
def get_layout
request.xhr? ? nil : 'normal_layout'
end
end
In your controller method, simply do this:
respond_to do |format|
format.js if request.xhr?
format.html { redirect_to :action => "index"}
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With