0

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();

  }
1
  • That javascript is really messed up. You've got code mixed into the declaration of your chart object. If you take that out and put it after the chart object initialization, you'll still get syntax errors because it becomes a mess of unsyntactical stuff after dataPoints. You need to work on your understanding of basic js syntax. Commented Mar 1, 2018 at 3:09

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I tried that but found that it's not the problem for some reason, the count variable was converted to int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.