Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respond to HTML requests made via AJAX in Rails

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?

like image 820
Mike Busch Avatar asked Sep 30 '09 15:09

Mike Busch


2 Answers

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
like image 176
DanSingerman Avatar answered Sep 28 '22 06:09

DanSingerman


In your controller method, simply do this:

   respond_to do |format|
      format.js if request.xhr?
      format.html { redirect_to :action => "index"}
    end
like image 25
JRL Avatar answered Sep 28 '22 07:09

JRL