Passing multiple rails variables to javascript
Asked Answered
C

7

7

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

Carse answered 25/11, 2011 at 1:9 Comment(1)
Related: https://mcmap.net/q/331114/-how-to-pass-ruby-variables-to-a-javascript-function-in-a-rails-viewErickericka
C
10

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.

Chrisman answered 16/8, 2012 at 9:41 Comment(0)
D
9

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!

Distrain answered 25/11, 2011 at 6:32 Comment(1)
I had trouble with this approach when @my_vars represented multiple entires from a database (e.g., @my_vars = MyVar.all in the controller, where MyVar is a model). Using <%= raw @my_vars.to_json %> remedied the issue. Thanks for your answer, it was helpful!Lan
S
2

I needed to get user's first name from database and pass the value to a javascript variable in JSON format.

I then declared a ruby variable named token which takes id and firstname attribute from the user table,

  ActiveRecord::Base.include_root_in_json = false

  @token = User.all.to_json(only: [:id, :firstname])

In the erb file, I used the following line,

var tokenList = <%= @token.html_safe %>
Saxhorn answered 13/1, 2014 at 14:40 Comment(0)
D
1

I think using Gon gem will be the best solution. also check out this video casts

Dayfly answered 19/2, 2013 at 9:37 Comment(0)
H
0

Maybe you should try to work with objects.to_json ;)

Handstand answered 25/11, 2011 at 1:24 Comment(0)
C
0

i found that gem client variable, it look promising. your configuration and variable are pass to client and you can easy get or set in client

Colburn answered 16/9, 2013 at 7:5 Comment(0)
K
0

Take a look at this.

http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs

One of the easiest ways is to use js.erb file, where you can do ruby tags to access variables that you defined in the controller action.

You need to use a respond_to block in the controller action, specifying the action to be able to respond to javascript.

items_controller.rb

class ItemsController < ApplicationController

  def action
    respond_to do |format|
      format.js
      #format.html {}    #  These are for allowing other types of formats to be responded to.
      #format.json {}    #  But they are not necessary for using this js.erb way of doing things.
    end
  end

end

/views/items/action.js.erb

$(div).html('The cat has erased your page');
Kirstenkirsteni answered 17/7, 2014 at 8:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.