How to pass Ruby array in Javascript to make a line graph

I am trying to make a webpage to display line graphs in my Ruby on Rails 2.3.14 application. I found a tool called JS Charts that allows me to create good charts using Javascript, but it's hard for me to send him the data he needs. Here's how to make a static line graph:

<script type="text/javascript"> var myData = new Array([1, 395], [2, 244], [3, 223], [4, 210], [5, 238], [6, 223], [7, 275], [8, 31]); var myChart = new JSChart('chartcontainer', 'line'); myChart.setDataArray(myData); myChart.draw(); </script> 

I put this code in stats.html.erb and it appears. However, I need to display the line graph data that I provide to him. A 2-dimensional array is created in the controller:

 >> @a => [[1, 395], [2, 244], [3, 223], [4, 210], [5, 238], [6, 223], [7, 275], [8, 31]] 

I have to use this variable in the view and set var myData for it with something like:

 var myData = "<%= @a %>"; 

I tried other things like:

 var myData = JSON.parse( "<%= @a.to_json %>" ); 

but nothing works. Is there anything I can do?

EDIT:

There was a problem with the array that the controller passed to the view (@a), which was empty. I was able to use:

 var myData = JSON.parse( "<%= @a.to_json %>" ); 

to display a line graph with the correct data being passed to the view.

+7
source share
1 answer

It looks like you worked it, but you can clean things up a bit:

 <%= javascript_tag do %> window.myData = <%=raw @a.to_json %>; <% end %> 

or in rails 3 you can be super HTML5 savy and use the data helpers to add your data as an attribute of some html tag:

 <%= content_tag "div", id: "myDiv", data: {stuff: @a} do %> <!-- some html stuff...--> <% end %> 

and then in javascript (with jQuery):

 var myData = $('#myDiv').data("stuff") 

and for the super modern, check out this railscast

+8
source

All Articles