Dodjs
Dodjs

Reputation: 819

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.

Upvotes: 11

Views: 13434

Answers (3)

LapinLove404
LapinLove404

Reputation: 1949

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

Upvotes: 9

traHfo
traHfo

Reputation: 83

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

Upvotes: 9

James
James

Reputation: 4807

You would need to create a file for create.js.erb or create.js.haml because it's the action being processed.

Here's a good tutorial:

http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/

Note: The article has an error where the call to escape_javascript has the S in script capitalized.

Upvotes: 3

Related Questions