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%>

<script>
  for( i = 0; i < data.length; i++ ) {
    alert(data[i]);
  }
</script>
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%>

<script>
  for( i = 0; i < all_data.length; i++ ) {
    alert(all_data[i]);
  }
</script>

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?

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

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