[Chartjs]-Chart.js and PHP

3๐Ÿ‘

โœ…

I guess you are doing it in an .js file. I guess your webserver ist not interpreting php code. Instead it is serving it as static javascript code.

Do it in a <script></script> in an .php file.

If you dont want to pass variable by variable to javascript:
Pass it as json.

An example can be found here:

1๐Ÿ‘

Make the array of colors
and pass your $row inside a foreach loop just like this.

foreach($row as $key=>$value)
            {
                $data[$key]['value']=(int)$value['id'];
                $data[$key]['color'] = $color[$key];
            }

And after that convert data into json like this

 var Data = <?php echo json_encode($dataArr['data']); ?>;

0๐Ÿ‘

This was helpfull!

I just changed my HTML doc to PHP, and then IT WORKS!

I am a rookie in code-develeper stuff, but my tip por MySQL cx is this.

Query:

<?php
session_start();
include_once "con.php"; #my conex in another doc

$query= "SELECT * FROM data ORDER BY id";
$result= mysql_query($query);

#For a simple first look, or rookies like me... I show the query result w/ an echo.  

while ($row= mysql_fetch_assoc($result)){
    echo $row['id'] . ' | ' . $row['mes'] . ' | ' . $row['valor1'] . ' % | ' . $row['valor2'] . ' % | ' . $row['valor3']. ' %' ."\n";


#This is what we need: I put data from my query in $setx, and then I use user3271851's code... it works!

    $set1= $row['valor1'];
    $set2= $row['valor2'];
    $set3= $row['valor3'];
}
?>

For the Chart, just like the post:

var pieData = [
  {
      value: <?php echo $set1; ?>,
      color:"#F38630"
  },
  {
      value : <?php echo $set2; ?>,
      color : "#E0E4CC"
  },
  {
      value : <?php echo $set3; ?>,
      color : "#69D2E7"
  }

];

var myPie = new Chart(document.getElementById("canvas").getContext("2d")).Pie(pieData);

P.S.: Sorry, my english is not good at all. ๐Ÿ™‚

Leave a comment