Question

I am creating a bar chart using chart.js however the values i want in the bar chart is a php array, one array for the values and one array for the labels. How do i add these arays to the bar chart. Currently I have this for the data for the bar chart:

ar barData = {
labels : ["January","February","March","April","May","June"],
datasets : [
    {
        fillColor : "#48A497",
        strokeColor : "#48A4D1",
        data : [456,479,324,569,702,600]
    }

]

}

I tried to do the following, but it still did not work:

<script type="text/javascript">
   var chartLabels= <?php echo $chartLabels; ?>
   var chartValues= <?php echo $chartValues; ?>
</script>

I would like to replace the 'labels' with a php array, as well as the 'data'

Was it helpful?

Solution

If $chartLabels or $chartValues are arrays, then you cannot echo them. You can just implode array as a js string and put it as a value for data like this:

var barData = {
  labels : ["January","February","March","April","May","June"],
  datasets : [
      {
          fillColor : "#48A497",
          strokeColor : "#48A4D1",
          data : <?php echo '['.implode(", ", $data).']'?>
      }
  ]
}

where $data is a normal php array.

OTHER TIPS

<script type="text/javascript">
   var chartLabels= <?php echo $chartLabels; ?>
   var chartValues= <?php echo $chartValues; ?>
</script>

Strange, that this code is not working. Do you use all of your javascript in ready handler? Also, note, that this variables should be declared and values assigned before you get data and draw data.

Another approach to achieve what you want:

You can use ajax request there. Before you draw graph you will send ajax request and get json response from the php server. It will contain all labels and all values, linked to labels. Now, all what you need it to parse this json and build graph.

Read about getJSON or parseJSON java script functions.

Your php script will just generate 2 arrays, then merging them into 1 big array and encoding them.

$values = array();
// get values
$labels = array();
// get labels
$result = array($values, $labels);
echo json_enocde($result);

Simple :)

Hope this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top