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: {data: @data, data1: @data1, data2: @data2} }
end
Now, - How should I access the data1 & data2 variables in my view file? - Do I need to modify window.data? I tried the below code though and it did not work out. Gave me argument error.
<%= javascript_tag do%>
window.data = <%= raw @data.to_json, @data1.to_json %>
<%end%>
Any leads would be appreciated.
Cheers!
The render json
call will render a single object, so try to store all the data in a single JSON object (or array):
respond_to do |format|
format.html
format.json { render json: {all_data: {data: @data, data1: @data1, data2: @data2}}}
end
On the front end:
<%= javascript_tag do%>
window.data = <%= raw @all_data.to_json %>
<%end%>
Now window.data
should have everything you need in window.data.data
, window.data.data1
, window.data.data2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With