Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery ajax and Rails 3 -> load content

I'm a beginner with ajax. I have a slider and a content div, the slider has links (event, news etc.), I want to create ajax load to content div (like Facebook).
I used Google, but I found very old articles (rails 2, but I use rails3).
In Rails 3 tutorial book has jQuery ajax with rails3, but it's very tiny.

I'am at this point:
I setting up my form with remote tag (:remote => true), and I renamed new.html.haml to _new.html.haml partial. I think I must create a new.js.erb file, which contains:

$(".menuitem").load("<%= escape_javascript(render('article/new')) %>") .content"); //just an idea

Is my logic is right?
If you have a good tutorial or example about rails and ajax, please share with me.

like image 652
Dodjs Avatar asked Mar 13 '11 14:03

Dodjs


2 Answers

The easiest would be to load your .content element onclick using jQuery:

$(".menuitem").click(function() {
  $(".content").load("/articles/new");
});

and render the form partial in your controller:

def new
  render :partial => 'form'
end
like image 108
traHfo Avatar answered Sep 22 '22 22:09

traHfo


I'd reccomand using jquery_ujs to handle this.

With Rails 3.1+, simply add gem 'jquery-rails' to your gemfile and //= require jquery_ujs in your application.js header.

Seting your links with :remote => true will then call the href using Ajax.

To load a blog post into your #content div you can then create a show_post.js.erb to render your post (assuming show_post is the action you use and you have a "_content_post.html.haml" that display the blog post content) :

$('#content').html('<%= escape_javascript (render :partial => "content_post") %>')

hope this help

like image 37
LapinLove404 Avatar answered Sep 23 '22 22:09

LapinLove404