Chartjs-How to create a bar chart with php data variables

1๐Ÿ‘

โœ…

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.

0๐Ÿ‘

<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.

Leave a comment