Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple rails variables to javascript

I have some values in ruby (variables and objects / hash) that I want to pass on to javascript on the rendered page. Currently I use these methods to simply write the javascript of declaring the variables at the client end.

  def declare_as_js_vars vars
    string = ""
    vars.each do |name, value|
      string += self.declare_as_js_var(name, value)
    end
    string
  end

  def declare_as_js_var name, value
    name.to_s + "='" + value.to_s + "';"
  end

The problem here is that I am unable to declare objects, and have to declare vars individually. I was wondering if there is some way in rails to easily do this because this is turning out to be quite a hack.

How should I pass variables and objects to javascript? Please provide some syntax example

like image 520
alik Avatar asked Nov 25 '11 01:11

alik


2 Answers

It' s a bit late but maybe it will help the others. There is a nice gem called gon which is very useful with passing variables from rails to javascript. You can also send the whole object.

In the controller you can have something like this

@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}
gon.your_int = @your_int
gon.your_other_int = 345 + gon.your_int
gon.your_array = @your_array
gon.your_array << gon.your_int
gon.your_hash = @your_hash
gon.your_object = Table.find(params[:id])

then in the javascript it will be available like

alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)
alert(gon.your_object.name)

There is also a railscast about it.

like image 112
Jaro Avatar answered Nov 15 '22 16:11

Jaro


I like to use script tags of type JSON to get the job done. It avoids polluting the global namespace and Rails happens to have great support for serializing objects to JSON.

You might use something like this in you view:

<script id="my_vars_json" type="text/json">
    <%= @my_vars.to_json %>
</script>

Then it's up to you to parse the JSON with JavaScript. I like to use jQuery:

$(function () {

    var myVarsJSON = $("#my_vars_json").html(),
        myVars     = $.parseJSON(myVarsJSON);

    console.log(myVars);

});

Hope that helps!

like image 41
bloudermilk Avatar answered Nov 15 '22 14:11

bloudermilk