Bharat Bharat - 2 months ago 16
jQuery Question

passing ruby arrays to javascript code (jquery) in a haml view in Ruby on Rails

I am displaying Highcharts graph on a haml template using jQuery/javascript. Here is a snippet showing the standalone graph from the demo code in HighCharts site:

:javascript

$(document).ready(function() {
$("#tabs").tabs();
new Highcharts.Chart({
chart: {
renderTo: 'volume_chart'
},
title: {
text: 'Logarithmic axis demo'
},
xAxis: {
tickInterval: 1
},
yAxis: {
type: 'logarithmic',
minorTickInterval: 0.1
},
tooltip: {
headerFormat: '<b>{series.name}</b><br />',
pointFormat: 'x = {point.x}, y = {point.y}'
},
series: [{
data: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512],
pointStart: 1
}]
});
});


This works fine. Now I am trying to set the series data from a ruby/rails array in the show.html.haml file like so:

...
- data_array = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
...
:javascript

$(document).ready(function() {
...
series: [{
data: "#{data_array}",
pointStart: 1
}]
});
});


This gives me the following error:

undefined method `to_js' for [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]:Array


How can I pass data_array from my ruby/rails code to the javascript/jquery code?

Appreciate any help.

Thanks.

Bharat

Answer
require 'json'

...

"#{data_array.to_json}"
Comments