3
votes

I am having trouble getting the values of my variables to pass to the var data portion of the drawchart function using google charts api. As is, my code currently displays the title of the chart, but no actual chart. If I change my data to be fixed numbers (1,2,3,4) instead of (h,i,j,k) then I get a chart exactly as I want. The problem is the data for the chart is not fixed. Any help would be great.

script type="text/javascript">
var h;
var i;
var j;
var k;

function myFunction() {
// h,i,j,k are calculated in here.   
};


  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  //i now reference h,i,j,k in the var data portion of the drawchart function
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['P&I',     h],
      ['Tax',      i],
      ['Insurance',  j],
      ['MI', k]
    ],
    false);

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

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
  };
</script>
1
Have you tried passing in the values of the numbers as strings to the chart (putting them inside of single quotes) - Yaco Zaragoza
What do you mean by data is not fixed? - Sahil

1 Answers

0
votes

Maybe it has something to do with timing.
When do you call myFunction?

This works...

var h;
var i;
var j;
var k;

function myFunction() {
  // h,i,j,k are calculated in here.   
  h = 2;
  i = 4;
  j = 6;
  k = 8;
};


google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart() {
  
  // set var values
  myFunction();
  
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['P&I',        h],
    ['Tax',        i],
    ['Insurance',  j],
    ['MI',         k]
  ]);

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

  var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
  chart.draw(data, options);
};
<script src="https://www.google.com/jsapi"></script>
<div id="donutchart" style="height: 320px; width: 320px;"></div>