Easy ajax forms with Rails 3 and jQuery
by Trevor Turk
Here’s a little trick you can use to dynamically create remote forms with very little effort. This particular example shows how to create checkboxes that, when clicked, will submit the form and update the record in the database all without leaving the page.
First, we’ll create the form anywhere in our app:
http://gist.github.com/548387?file=index.html.erb
Note the remote => true form option and submittable css class.
In order to accept the form, we’ll need to create the corresponding controller action:
http://gist.github.com/548387?file=tickets_controller.rb
Then, we’ll use a little bit of jQuery that tells the browser to submit the form if any element with the class submittable is changed:
http://gist.github.com/548387?file=application.js
Finally, we may want to perform some action after the form is submitted:
http://gist.github.com/548387?file=update.js.erb
This is just a quick little example, but you can imagine how the technique could be applied to a lot of different things. Rails 3 and jQuery make it really, really easy to submit forms on the fly without reloading the page or even having the user click submit.
wow…! so easy
Thanks for posting this tutorial.
I followed you instructions, but it didn't work, it actually invoked the 'update' action, but then it tried to render the update.js.erb in the browser, any idea what's going wrong?
Hao, I'm not sure… did you add the Rails jQuery js file(s)? Maybe try this:
http://github.com/indirect/jquery-rails
Trevor, I've added that gem to my Gemfile.
From the Firebug script console, I can see a warning messsage saying "Resource interpreted as document but transferred with MIME type text/javascript.", any idea about this?
Thanks a lot
Sorry, Hao, but it's really difficult for me to troubleshoot this from blog comments.
Trevor, never mind, thanks for the help
can u upload an example of this tutorial in github..? pls
Hao,
Make sure you put return false; at the end of the js function.
$('.submittable').live('change', function() {
$(this).parents('form:first').submit();
return false;
});
Fantastic. Worked for me. Thanks for the example (I made an update.js.erb file and work with that. Better for me!)
Me think i love you. 3 hours looking for a solution, and it was so simple.
Thx!!
I am wondering if the same thing can be used for form_tag.
whoda thunk it! $('#form_id').submit() …so easy…once again proving the awesomeness of rails _and_ jQuery!
Hi Trevor,
Thanks for sharing this useful information. This helped me, when I was implementing auto-select drop down. (e.g. Country -> States -> Cities)
Once again, much much thanks for sharing this.
Best Regards
Puneet
Hello, Trevor.
I used your concept successfully with jQuery 1.6 but it broke after updating to version 1.6.1. Do you have any idea why?
Thanks for sharing this worked great with Rails 3, Ruby 1.9.2 and jquery 1.7.2
Great post, thanks!