0

I am using google charts by putting javascript straight into my haml file. I've tried a couple of other things (such as the chartkick gem), but I was still having a similar problem as the one I'm currently having.

The issue is that when I load the page from the url, or refresh the page, google charts works fine. However, when I link to the page from a link on another page, the chart doesn't load and the console spits out a Uncaught ReferenceError: google is not defined

Any ideas? Even when I used the gem, it would load when I refreshed the page, but not if I linked directly to it. I thought it may be a turbolinks issue so I disabled turbolinks on that specific page, and then globally, but I am still having the same problem. Below is my code

.row.show-characteristics
  .col-md-3.col-xs-12
  .col-md-3.col-xs-12
  .col-md-3.col-xs-12
  .col-md-3.col-xs-12.google-chart
    #google-donut-chart
%script{type: "text/javascript", src: "https://www.google.com/jsapi"}
%script{type: "text/javascript"}
  :plain
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work',     11],
          ['Eat',      2],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);

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

        var chart = new google.visualization.PieChart(document.getElementById('google-donut-chart'));

        chart.draw(data, options);
      }
Arvind
  • 2,671
  • 1
  • 18
  • 32
Hopscott
  • 251
  • 2
  • 6

2 Answers2

1

It turned out to be an issue with turbolinks. I'm not entirely sure, but I think jquery was only being loaded on refresh. I removed turbolinks from the project to fix it.

Hopscott
  • 251
  • 2
  • 6
1

Add your js code inside bellow code, it is issue with turbolink

$(document).on('ready page:load', function () {
  // Actions to do
});

also you can find more details here

Community
  • 1
  • 1
Arvind
  • 2,671
  • 1
  • 18
  • 32