Misha Moroshko
Misha Moroshko

Reputation: 171321

Rails 3: How to make an Ajax call?

I would like to have a link (is there a better option?) on my page which will make an Ajax request when clicked. (I would like to update a field in my database when the link is clicked.)

What is the simplest way to achieve this ?

Could you refer me to some tutorials ?

Upvotes: 14

Views: 11805

Answers (2)

Jinyoung Kim
Jinyoung Kim

Reputation: 2211

Really simple. In your view, have a link/button like so. Important bit being :remote => true

<%= link_to 'Update Thingy', update_thingy_path, :confirm => 'You sure you wanna update?', :remote => true %>

or

<%= button_to('Update Thingy', {:action => 'update_thingy', :thingyid => 314}, :method => :get, :remote => true) %>

Obviously, you have to get update_thingy_path to resolve to some action as normal. The difference is when you render you are going to be rendering some *.js.erb instead of *.html.erb. In that update_thingy.js.erb, you just put whatever javascript you want to run in the client. You might wanna notify the user that the update happened for example (in jQuery):

$('#notice').html("Thingy was update.")

Or if whatever javascript you're returning is really simple, in the controller you can do something like the following instead of having a whole js.erb for a one-liner.

render :js => "alert('Blah')"

Upvotes: 24

Lynn Crumbling
Lynn Crumbling

Reputation: 13357

You're really going to be using two technologies to accomplish this: javascript on the client-side, and rails on the server-side.

The general idea is that you want to:

(1) add your web methods on the server side with rails, and then
(2) use something like jQuery to get your client-side js calls up to the server to fire off the web methods.

Two writeups I found by googling for : rails3 ajax

http://www.stjhimy.com/posts/7-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript

http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

API Reference for using jQuery's ajax post() method:
http://api.jquery.com/jQuery.post/

Upvotes: 3

Related Questions