Making a ajax request from rails

Making a AJAX request in rails is pretty simple. Just follow the below example. It will take you to the particular  method (ex.., todo_fix method in the rooms controller) as used in my example. Then in controller you can perform your operation and do the render part.

In View File

Sample Rails code

<% todo_item=TodoItem.find(:first) %>

<a href=”javascript:call_this(<%= %>);”>Add a New To-Do Item</a>

JavaScript function in the same file

function call_this(a)
var url = “/rooms/todo_fix”;
var pars = “new_todo=” + a;
var target = ‘idresult’;
var myAjax = new Ajax.Updater(target,url, {method: ‘post’,parameters: pars});


Ajax Request in Rails 2 & Rails 3

AJAX request from anchor tag

Rails 2
<a href="#" onclick="new Ajax.Request('/comments/1', {asynchronous:true, evalScripts:ture, method:'delete'}); return false;">Destroy</a>

Rails 3
(unobstrusive JavaScript in Rails 3) 
<a href="/comments/1" data-remote="true" data-method="delete">Destroy</a>