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
asked Apr 16, 2013 at 22:14
HeshamW
3471 gold badge4 silver badges6 bronze badges
1 Answer 1
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.
answered Apr 16, 2013 at 22:39
Benjamin Manns
9,1785 gold badges40 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
HeshamW
It does not work, It gives me a blank page. My array should be something like that : [['task', 'points'], ['A', 20]]
Benjamin Manns
What is the code that generates your
@statistics array? If you run the code in your rails console, what is the output?HeshamW
I just have this in the console : @statistics = [['task', 'points'], ['A', 20]]
Benjamin Manns
[['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?Explore related questions
See similar questions with these tags.
default