How to asynchronously load a partial page in rails How to asynchronously load a partial page in rails ajax ajax

How to asynchronously load a partial page in rails


First put an empty, placeholder div in the main response

<div id="pink-dancing-elephants"></div>

and then add a little jQuery to the page

$.ajax({    url: "/elephants/dancing",    cache: false,    success: function(html){      $("#pink-dancing-elephants").append(html);    }});

and have the action that responses to /elephants/dancing/pink return the blob of HTML that you want to have fill up the div. In the action that is invoked by the AJAX request, you'll want to render with :layout => false to keep the returned blob of HTML from including the entire frame. E.g.

# elephants_controller.rbdef dancing  @elephants = #whatever  render :layout => falseend

This would render the template in views/elephants/dancing.html.erb.


There's a simpler way to do it compared to @cailinanne.

Using her same example, but I tend to use this technique to update a div, so my div would first have that partial:

<div id="pink-dancing-elephants">   <%= render "elephants/dancing", elephant: some_thing  %></div>

But then use the jQuery load method:

$("#pink-dancing-elephants").load("/elephants/dancing");

This will return the whole partial. Be sure to use layout: false, and optionally set params. I tend to use a partial like this

# elephants_controller.rbdef dancing  render "elephants/_dancing",          locals: { elephant: some_thing },         layout: falseend

This would render the template in views/elephants/_dancing.html.erb.

NOTE the underscore in the partial name for the controller method and how you don't use it when calling render in the view.