Páginas

Saturday, November 6, 2010

Passing data from a jQuery script to a controller method in Rails using Ajax

First of all you have to write your script to get the data and store it in variables. This code should be written either in public/javascripts/application.js or in a new file in the same directory and then included in the HTML, like so:

<%= javascript_include_tag 'name_of_file' %>
or

<%= javascript_include_tag :defaults %>

to include the application.js file.

Have in mind though that this includes must be done after including the jquery.js, and that jQuery can affect other scripts that use prototype. Therefore, if you are using any code that needs prototype or just as a good practice, the first line of your jQuery script should be jQuery.noConflict();.

This being said, the way you pass your data to the controller is through an Ajax post, which is something like this:

$.post(path,{ "string1": variable1,"string2": array1},null,"script");

Check the jQuery documentation for more details.

The path variable should be in the form controller/action, so that the message is sent to the desired action.

The next thing to do is to create the action in the controller that will receive the message. This action can respond to different kind of requests in different ways, what I mean is that if it is an HTTP request it behaves one way, and if it is our Ajax request it behaves another.

This separation of behaviours is achieved with respond_to like this:

respond_to do |format|
format.html { redirect_to :action=>"list" }
format.js
end


As it is easily perceivable, for an HTTP request it redirects to the action named list of the same controller and renders it. What it does in the case it receives an Ajax request might not be that obvious, because the code that will be run can be written in a file called action_name.js.erb that has to be in the views/controller directory.

This file can be something as simple as this:

$("#justForTest").html('
params[:actions]
');


One last thing for this to work is that the post request in our client side script must be an Ajax request. This can be done by adding .js to each path or by adding this setup code to the top of your scripts file:


jQuery.ajaxSetup({
'beforeSend':function(xhr) {xhr.setRequestHeader('Accept','text/javascript')}
})


This should make your request work as intended. Have fun with jQuery and Ruby on Rails, which are very powerful tools for any web developer.

No comments: