Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a Ruby array to 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, which allows me to create nice graphs using Javascript, but I am having trouble sending it the data it needs. Here is the way 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 that code into stats.html.erb, and it shows up. However, I need it to display line graph data that I provide it. 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 should be able to use that variable in the view, and set var myData to it, with something like:

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

I tried other things like:

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

but nothing seems to work. Is there anything I can do?

EDIT:

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

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

to display the line graph with the right data being passed into the view.

like image 618
Eric Avatar asked May 02 '12 04:05

Eric


1 Answers

Seem's like you got it working 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 att of some html tag:

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

and then in then in the javascript (with jQuery):

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

and for the super keen, check out this railscast

like image 59
Matthew Avatar answered Oct 30 '22 18:10

Matthew