Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Charts in Rails 3.1 Ajax Partial

I've been working with Google charts with no problems but I've now got to a point where I need to display a chart inside of an Ajax-rendered partial.

Obviously nothing is showing. I know it's something to do with the Java trigger to build the chart not being activated, but I need some help with exactly what it is I need to do...

Currently I 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>
like image 840
user1051849 Avatar asked Jan 19 '12 14:01

user1051849


1 Answers

In your main page keep these (no need to load google charts in the 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 you need to do something like below (assuming you use jQuery). The point is to execute the js code after the dom is loaded which is what $(function() {....}) does:

<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 like jQuery will save you many hours of browsers inconsistencies for knowing when the dom is properly loaded.

like image 170
Yoni Baciu Avatar answered Oct 20 '22 06:10

Yoni Baciu