stephen odiver
stephen odiver

Reputation: 9

How to add data to pie chart Javascript

I am trying to display the percentage of pets per owner in a pie chart, how do i push data to the piechart? the for loop keeps getting a SyntaxError: Unexpected token var. here's my code.

window.onload = function() {
var count = "<?php echo($i)?>";
var name = [];
var per = [];
var j = -1;

var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
    text: "TB_PET"
},
data: [{
    type: "pie",
    startAngle: 240,
    yValueFormatString: "##0.00\"%\"",
    indexLabel: "{label} {y}",

Error here-->for(var i = 0; i < count; i++){
 name[i] = document.getElementById(i).value;
 per[j] = document.getElementById(j).value;

dataPoints: [
{y: per[j], label: name[i]}
]

  j--;
  }

  }]
  });
  chart.render();

  }

Upvotes: 0

Views: 535

Answers (2)

Randy Casburn
Randy Casburn

Reputation: 14165

You cannot iterate inside the object literal (configuration for the chart) that is passed as a parameter to a function call.

Iterate over you data prior to the new CanvasJS.Chart(...) call, and pass the variable as part of the config object.

Iterate here

var dataPoints = []; 
for(...){
  dataPoints.push(..);
]

then pass dataPoints in as below

var chart = new CanvasJS.Chart("chartContainer", {
  animationEnabled: true,
  title: {
    text: "TB_PET"
  },
  data: [
    {
      type: "pie",
      startAngle: 240,
      yValueFormatString: '##0.00"%"',
      indexLabel: "{label} {y}",
      dataPoints: dataPoints

    }
  ]
});
chart.render();

Upvotes: 1

Joshua
Joshua

Reputation: 182

Note: This would be a comment if my rep was higher

I'm not familiar with php returns, but I would first start with manually changing the 'count' variable to be an actual number before moving forward. It appears that your for loop is evaluating the 'count' variable as a string and then throwing the error you're seeing.

https://airbrake.io/blog/javascript-error-handling/unexpected-token

Upvotes: 0

Related Questions