20 October 2008 ~ Comments Off

Using remote_function

This wonderful built-in function is a great way to make easy Ajax calls. In this example I will show you how to use remote_function with the onClick call, and also within a JavaScript function.

First, lets make a checkbox called finish; this link will send the id of the item to the database to be updated. The item will be a todo and we will be using the list.html.erb and the todo_controller.rb.

In the view named: list.html.erb


remote_function(:url => {:action => 'finish', :controller => 'todo',
:id => todo.id})

Now once the checkbox is clicked it will them make the Ajax call to the todo_controller.rb with the method finish.

In the controller: todo_controller.rb


def finish
	@todo = Todo.update(params[:id], :status => '1')
	if @todo.save
		render :update do |page|
		page.replace_html 'thedivID' + params[:id], 'Finished!'
		end
	end
end

The above code will first update the database setting the status from 0 to 1 (1 = finished and 0 = unfinished). Next we check if the update was successful, after that we render the update to the page. By using render :update, we can replace the html in side of the div or other element with the text ‘Finished’.

Note you can use remote_function in any way you see fit, ie: onclick, onload and others.

Passing another var with remote_function. lets say i want to pass the user id, list id and, the todo id. How would we do this with the remote function?

We know know the link should look like this: /todo/finish/17?todoid=72&userid=100, but how do we do this with rails? Below is how to do just that;


remote_function(:url => {:action => 'finish', :controller => 'todo',
:id => list.id, :todoid => todo.id, :userid => @user.id})

Comments are closed.