Google Charts in Rails 3.1 Ajax Partial

I worked with Google charts without any problems, but now I realized that I need to display the chart inside partial Ajax.

Obviously nothing is visible. I know this has to do with the Java trigger to create a diagram that is not activated, but I need help with what I need to do ...

I currently have something like this (non-Ajax):

<html> <head> <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 = new google.visualization.DataTable(); data.addColumn('string', 'Year'); data.addColumn('number', 'Sales'); data.addColumn('number', 'Expenses'); data.addRows([ ['2004', 1000, 400], ['2005', 1170, 460], ['2006', 660, 1120], ['2007', 1030, 540] ]); var options = { width: 400, height: 240, title: 'Company Performance', vAxis: {title: 'Year', titleTextStyle: {color: 'red'}} }; var chart = new google.visualization.AreaChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <div id="chart_div"></div> </body> </html> 
+6
source share
2 answers

Save them on the main page (no need to download Google charts in partial):

 <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); </script> 

In your partial part, you need to do something like below (if you are using jQuery). The point is to execute the js code after which the dom loads, which is what $ (function () {....}) is:

 <div id="chart_div"></div> <script type="text/javascript"> $(function() { drawChart(); }); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Year'); data.addColumn('number', 'Sales'); data.addColumn('number', 'Expenses'); data.addRows([ ['2004', 1000, 400], ['2005', 1170, 460], ['2006', 660, 1120], ['2007', 1030, 540] ]); var options = { width: 400, height: 240, title: 'Company Performance', vAxis: {title: 'Year', titleTextStyle: {color: 'red'}} }; var chart = new google.visualization.AreaChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> 

Using a library such as jQuery will save you many hours of browser inconsistency, knowing when dom is loaded correctly.

+8
source

Replacement

 google.setOnLoadCallback(drawChart); 

from

 $(function() { drawChart(); }); 

did the trick for partial AJAX! Thanks for the help, earlier the DOM rebooted, but the diagrams were not inserted.

0
source

Source: https://habr.com/ru/post/906400/


All Articles