Suppose you have a page with two columns of content. For whatever reason, you wish to retrieve the HTML content of one of those columns after the page has loaded, via an AJAX re
I am using the method described in @cailinanne's comment to Dan L's post and it's worked well for me. I like the readability of the data tag that's attached to the div. Within your html you can see exactly what's going to load into that div, and you don't have to add any new JS if you want to add this functionality to multiple divs or pages.
Taking from this article: http://tech.thereq.com/post/16479390885/loading-page-content-via-ajax-in-rails-3-1
The simplest way to do this to use the jQuery load method.
$("#comments").load("/blogs/2/comments");
The awkward part is the AJAX path (/blogs/2/comments) which clearly changes according to which blog we are viewing. If we followed the jQuery documentation exactly, we could just plop a script tag in the middle of our HTML body, so that in our template file we might have something like
# show.html.erb
Yuck. Not a fan of javascript mixed into my template files.
What to do instead? Follow the pattern suggested by Rails UJS and take advantage of the new HTML data- attributes.
First, when you want to load AJAX content in your page, do the following in your template
#show.html.erb
Second, add the following to your application.js
# application.js or any JS file loaded within application.js
$("div[data-load]").filter(":visible").each(function(){
var path = $(this).attr('data-load');
$(this).load(path);
});
Third, set up a route that matches a get request to blog_comments (type rake routes
to see how your routes are named)
# routes.rb
# ajax load at page load
get "/blogs/comments" => "blogs#comments"
And voila! Your comments div will magically be filled by whatever is returned by the /blogs/3/comments path!