Zack Shapiro
Zack Shapiro

Reputation: 6998

Passing values from a Ruby on Rails controller into Javascript to render

I've got this JS highchart that I'm trying to pass some values into that are calculated in my pages_controller. I've tried this with global and instance variables and neither seem to work in rendering. I guess the value isn't passed in.

In my pages_controller I have:

> @nil_ref = (@counts[nil]/total.to_f)*10
> @email_ref = (@counts["email"]/total.to_f)*10
> @cpc_ref = (@counts["cpc"]/total.to_f)*10
> @display_ref = (@counts["display"]/total.to_f)*10

And then in my /public/highcharts.js file I have:

var chart1; // globally available
   $(document).ready(function () {
       var chart = new Highcharts.Chart({
           chart: {
               renderTo: 'container',
               type: 'pie'
           },
           xAxis: {
               categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
           },
           yAxis: {   
           },
           legend: {
               layout: 'vertical',
               floating: true,
               backgroundColor: '#eeeeee',
               align: 'right',
               verticalAlign: 'top',
               y: 60,
               x: -60
           },
           tooltip: {
               formatter: function() {
                   return '<b>'+ this.series.name +'</b><br/>'+
                       this.x +': '+ this.y;
               }
           },
           plotOptions: {
           },
           series: [{
               data: [<%= @nil_ref %>, <%= @email_ref %>, <%= @cpc_ref %>, <%= @display_ref %>] //These need to be global vars        
           }]
       });
   });

When I inspect the element in Chrome, I get Uncaught SyntaxError: Unexpected token at the line with the Ruby tags in the JS.

Any ideas how to successfully pass these values in?

Upvotes: 0

Views: 815

Answers (1)

cuzzea
cuzzea

Reputation: 1535

if the RoR data are strings you need to do like so:

data: ["<%= @nil_ref %>", "<%= @email_ref %>", ...

Upvotes: 1

Related Questions