Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
Jorge Israel Peña Avatar asked Feb 18 '11 07:02

Jorge Israel Peña


3 Answers

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
like image 82
Pan Thomakos Avatar answered Sep 30 '22 10:09

Pan Thomakos


You could pass a GET parameter in the URL and put a condition in your controller:

def show
  render(:layout => false) if params['partial'] == 'true'
end

And javascript:

$('#container').load('/posts/34?partial=true')
like image 30
Andrew Marshall Avatar answered Sep 30 '22 08:09

Andrew Marshall


If you want to support regular and AJAX requests you'll want to use a respond_to block.

Like so

respond_to do |format|
  format.html # renders index.html.erb automatically
  format.js { render 'show', :content_type=>'text/html', :layout=>false }
end
like image 29
aNoble Avatar answered Sep 30 '22 10:09

aNoble