Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 443
Misha Moroshko Avatar asked Mar 12 '11 03:03

Misha Moroshko


People also ask

How AJAX works in rails?

Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response. The response is then displayed for the user on a new page.

What is AJAX in JavaScript with example?

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


1 Answers

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')"
like image 173
Jinyoung Kim Avatar answered Sep 25 '22 01:09

Jinyoung Kim