How do I include HTML in a JS Rails response?

James A. Rosen picture James A. Rosen · Nov 19, 2008 · Viewed 13.3k times · Source

I have a FooController that responds to HTML and JS (AJAX) queries:

# app/controllers/foo_controller.rb:
class FooController < ApplicationController
  layout 'foo'
  def bar
    respond_to do |format|
      format.html # foo/bar.html.erb
      format.js   # foo/bar.js.erb
    end
  end
end

The templates to support it:

# app/views/layouts/foo.html.erb:
<html>...<%= yield %>...</html>

# app/views/layouts/foo.json.erb:
<%= yield %>

And an AJAX template in which I want to render a partial:

# app/views/foo/bar.js.erb:
dojo.byID('some_div').innerHTML = "<%= escape_javascript(render(:partial => 'some/partial')) %>";

If the JS template just has plain old JS in it (like alert('hi');), it uses my JS template. When I put in the render(:partial), though, it makes the whole response use the HTML template, which means it's no longer valid JS.

A possible solution is to use a function for the layout:

class FooController < ApplicationController
  layout :choose_layout
  ...
  private
  def choose_layout
    return nil if request.xhr?
    'foo'
  end
end

But my version should work! Why doesn't it?

Answer

mwilliams picture mwilliams · Nov 19, 2008

The most recent Railscast covers this topic (using jQuery).

I'm not quite seeing where you might be going wrong, but here's a snippit from the Railscast that works just fine to render a partial:

// views/reviews/create.js.erb
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();

Where are you storing your Javascript? Do you have an Application.js that you're keeping things in? If so, are you including "dojo" before "application" in your javascript_include_tag?