user3422637
user3422637

Reputation: 4229

Pass Rails JSON variable to javascript variable

I have a Global JSON variable in my Ruby on Rails controller. It looks like this @rails_side_json = { :name => 'Will', :age => 23 }.to_json

I want this to be assigned to my javascript variable (var javascript_side_json) which resides in my javascript file named custom.js.erb

The value in javascript_side_json variable after the assignment is done should be equivalent to me writing var javascript_side_json = {"name": "Will", "age": 23 };

I am not able to achieve this by writing var javascript_side_json = <%= @rails_side_json %>

How can I achieve this? Do I need to make changes in multiple files?

Upvotes: 14

Views: 14025

Answers (3)

Christian
Christian

Reputation: 888

The above answers didn't work for me. Therefore I'm posting a solution that is working for me.

# Rails
@server_variable = some_variable.to_json.html_safe


// Javascript
let var = JSON.parse('<%= escape_javascript(@server_variable)  %>')

Upvotes: 0

Zero Fiber
Zero Fiber

Reputation: 4465

The JSON will be escaped by default. You can tell the view to use in the code using raw

var javascript_side_json = <%= raw @rails_side_json %>

Upvotes: 9

Muntasim
Muntasim

Reputation: 6786

You are almost done. Just need to make sure your json is safe html:

var javascript_side_json = <%= @rails_side_json.html_safe %>;

or

var javascript_side_json = <%=raw @rails_side_json %>;

Upvotes: 25

Related Questions