Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I pass a Ruby array to Javascript to make a line graph
    primarykey
    data
    text
    <p>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:</p> <pre><code>&lt;script type="text/javascript"&gt; 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(); &lt;/script&gt; </code></pre> <p>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:</p> <pre><code>&gt;&gt; @a =&gt; [[1, 395], [2, 244], [3, 223], [4, 210], [5, 238], [6, 223], [7, 275], [8, 31]] </code></pre> <p>I should be able to use that variable in the view, and set <code>var myData</code> to it, with something like:</p> <pre><code>var myData = "&lt;%= @a %&gt;"; </code></pre> <p>I tried other things like:</p> <pre><code>var myData = JSON.parse( "&lt;%= @a.to_json %&gt;" ); </code></pre> <p>but nothing seems to work. Is there anything I can do?</p> <p>EDIT:</p> <p>There was an issue with the array the controller passed into the view (@a), which was empty. I was able to use:</p> <pre><code>var myData = JSON.parse( "&lt;%= @a.to_json %&gt;" ); </code></pre> <p>to display the line graph with the right data being passed into the view.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload