0

I'm displaying a Google Charts Pie Chart on a Rails 5 app Page.

The chart only displays if I click refresh, not on the initial page load.

It appears i'm not the first to have this problem, but none of the solutions i've tried have been successful - i.e. setting a timeout.

Any guidance would be much appreciated.

/layouts/application.html.erb

<head>
...
<%= yield :google_chart_scripts %>
...
</head>

/views/organisations/show.html.erb

<% content_for :google_chart_scripts do %>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});

            google.charts.setOnLoadCallback(drawChart);
            function drawChart() {
               var data = google.visualization.arrayToDataTable([
                  ['Effort', 'Amount given'],
                  ['Debt', 100.00],
                  ['Equity', 900.00]
               ]);

               var options = {
                  colors:['#f75b52','#363e4a'],
                  pieHole: 0.4,
                  pieSliceText: 'percentage',
                  chartArea: {'width': '90%', 'height': '90%'},
                  legend: 'none'
               };

               var chart = new google.visualization.PieChart(document.getElementById('piechart')%>'));
               chart.draw(data, options);
               }

</script>
<% end %>

2 Answers2

0

That's issue with turbolink, try wrap js code with :

$(document).on('ready page:load', function () {
  // your google chart js
});

more detail for that issue here

Community
  • 1
  • 1
rails_id
  • 8,120
  • 4
  • 46
  • 84
0

You face this problem often when you use turbolinks. One solution is using jquery-turbolinks gem.

gem 'jquery-turbolinks'

You just add jquery.turbolinks right after including jquery in the application.js file. (or the manifest file you are using)

It will bind the Rails Turbolinks events to the document.ready events so you can write your jQuery easily. This will help in other such cases if occur in your project

Hope This Helps.

Mayank
  • 727
  • 6
  • 9