Pregunta

I am using Chart.js to create charts on my site. The data needs to come from a database so PHP needs to be inside the javascript.

This is what I have: (as just testing not the database part yet)

<?php
   $set1 = 20;
   $set2 = 30;
   $set3 = 40;
?>

And then to create the pie chart I have:

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

With this code I recieve this error:

Uncaught SyntaxError: Unexpected token < when it reached the first <?php call.
¿Fue útil?

Solución

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:

Otros consejos

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']); ?>;

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top