Jorge Israel Peña Jorge Israel Peña - 1 year ago 129
Ajax Question

how to load an html fragment in rails with jquery?

I am wondering how I may

jQuery.load
an HTML fragment returned by a model's
show
action. For example,
$("#container").load("/posts/34")
. The problem with this is that it returns the view I want embedded in the layout, as if I were to visit that url in the browser. I only want the
Post
's
show
HTMl fragment.

Thanks!

Clarification: I want the
show
view to continue to render within the application layout when going to the
show
action in my browser. I'm merely trying to figure out how to fetch only the html of the
show
view for when I want to load it asynchronously with jQuery. I have seen guides in which they create
show.js.erb
and then render the html view there, but it seems pretty messy to me, escaping all of that html for javascript. If this is the accepted and proper way of doing this though I guess I'll follow the standard. I was just wondering if it were possible to only fetch the html of a particular view.

Answer Source

You can use :layout => false in your render statement to return the fragment without the layout:

def show
  ...
  render(:layout => false) if request.xhr?
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download