0

I want to pass a 2d array from ruby to javascript.

I currently have this id in the view:

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable(<%= @statistics %>);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

@statistics is a 2d array comin from the controller

1 Answer 1

3

The method you are looking for is #to_json.

var data = google.visualization.arrayToDataTable(<%= @statistics.to_json %>);

For example:

[["abc", 123], ["def", 456]].to_json # => [["abc",123],["def",456]]
[[1, 2], [3, 4], [5, 6]].to_json # => [[1,2],[3,4],[5,6]]

If your @statistics variable is not a plain 2D array, it may require additional processing before you output it to JSON.

Sign up to request clarification or add additional context in comments.

4 Comments

It does not work, It gives me a blank page. My array should be something like that : [['task', 'points'], ['A', 20]]
What is the code that generates your @statistics array? If you run the code in your rails console, what is the output?
I just have this in the console : @statistics = [['task', 'points'], ['A', 20]]
[['task', 'points'], ['A', 20]].to_json gives me [["task","points"],["A",20]], so it looks like there is something else going on. Can you post the exact controller and view code you are using?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.