Pass multiple variables to render json in rails cotroller

I am trying to pass the data from controller to javascript. This is how
you do it,

respond_to do |format|
format.html
format.json { render json: {data: @data} }
end
And then in your view file, you should do this:

<%= javascript_tag do%>
window.data = <%= raw @data.to_json %>
<%end%>

Make sense. Right?

However, above code is when you are passing only one variable in json
code i.e. data variable. What I need to do is to pass multiple variables
to my javascript code.

It should be done as:

respond_to do |format|
format.html
format.json { render json: {all_data: {data: @data, data1: @data1,
data2: @data2}}}
end

Now, - How should I access the data1 & data2 variables in my view file?

My view file has:

<%= javascript_tag do%>
window.data = <%= raw @all_data.to_json %>
<%end%>

Above alerts me NULL. What have I done wrong? Where have I messed up?

Any leads would be appreciated.

Cheers!

Hi, your view is html?

2015-04-11 4:01 GMT+10:00 Hemant B. [email protected]:

Controllers with respond_to format block responds with one format for
each
request. I belief you requested html format so this should works for
you:

respond_to do
|format|
  format.html { @all_data = {data: @data, data1: @data1, data2: @data2} }
  # if you still need respond to json you
should uncomment/not delete next line
  # format.json { render json: {all_data:
{data: @data, data1: @data1, data2: @data2}}}
end

2015-04-12 12:25 GMT+10:00 Dmitry S. [email protected]:

sorry, this should be more readable

respond_to do |format|
format.html { @all_data = {data: @data, data1: @data1, data2: @data2}
}

if you still need respond to json you should uncomment/not delete

next
line

format.json { render json: {all_data: {data: @data, data1: @data1,

data2: @data2}}}
end

2015-04-12 12:44 GMT+10:00 Dmitry S. [email protected]: