I spent a good chunk of time getting AJAX to work properly in rails 3 using jQuery. My sticking point was that the basic RJS I was using (like page.replace_html) was not working unless I installed and patched the jrails plugin. What I learned was not to use RJS at all, just write your jquery directly. The jrails plugin used to replace all the RJS function calls but those are being phased out, jrails is now officially obsolete.
Quick summary to get things working:
<%= csrf_meta_tag %>
- Now you can use :remote => true inside and link_to, button_to, form_tag, etc and it should work
- When you create the view that responds to the remote call, name it action.js.erb rather than action.js.rjs. If your view is an RJS file it will contain something like:
page.replace(‘#div_id’, render( @object ) )
Rails will try to generate prototype code using this which won’t work with jquery. Instead, when you name it an ERB file, it will contain straight jquery code like:
These references were all helpful:
12 Responses to “Getting AJAX to work in Rails 3 with jQuery”
November 29th, 2010 at 5:09 am
February 15th, 2011 at 5:31 am
Thanks a ton! You saved the day for me!
March 11th, 2011 at 4:27 am
Nice and simple. :) :) :D
March 20th, 2011 at 11:36 pm
Thanks, I haven’t found an explanation that put the steps to using jquery this succinctly. I was very confused about some tutorials using .js.erb vs. js.rjs; didn’t understand about why page.replace_html wasn’t working, and the fact that jrails is now obsolete! Thanks!!
May 16th, 2011 at 2:36 am
I am stuck and a bit desperate at this stage :), I have followed many instructions to get this running but none of them worked (they are similar to yours.)
Any ideas where I should be digging?
Puneet Pandey Says:
May 18th, 2011 at 1:43 pm
Thanks for sharing this. Understanding Rails3-ujs, was tough initially, but after getting good hands on experience, things are working pretty faster. :)
September 19th, 2011 at 5:44 am
Thanks Keith. This was very helpful
February 22nd, 2012 at 11:33 pm
Thanks Keith. you save my day.you know how much it matters………..
March 11th, 2012 at 6:40 am
I got an error
“NetworkError: 406 Not Acceptable – http://localhost:3000/answers/agree.7“
May 23rd, 2012 at 4:53 pm
But how do you handle the data on the controller and call the action.js.erb?
Muriel Salvan Says:
August 1st, 2012 at 2:35 am
For Ajax pages refresh, you can also use the rails-ajax gem. It automatically ajaxifies your application and updates only the pages content without refreshing the layout by default.
Can be customized at will and handles browser’s history, bookmarking, scripts executions, forms, redirections…
October 4th, 2012 at 5:55 am
Will you please explain it by an example so that everybody can understand it better.