Reputation: 61
I'm trying to add a php variable in data: in chart.js. The examples say data: [<?php echo $dates ?>],
This will do, but when I try to do this, it immediately gives me an error that < is an unexpected token. which in a way makes sense. I put it in a string ["<?php echo $dates ?>"]
, but then I do not get any results.
while ($stelling = mysqli_fetch_array($records1)){
$Timer = date('M, Y', strtotime($stelling['Timer']));
$Wheight = $stelling['Wheight'];
$Title = $stelling['Title'];
$Timers = '';
$Wheights = '';
$Titles = '';
$Timers = $Timers.'"'.$Timer.'",';
$Wheights = $Wheights.$Wheight.',';
$Titles = $Titles.$Title.',';
$Timers = trim($Timers, ",");
$Wheights = trim($Wheights, ",");
$Titles = trim($Titles, ",");
}
echo '<script src="script/graph.js"></script>';
The script file:
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Time',
data: ["<?php echo $Timers ?>"],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}
I expect the graph to show the data that is stored in the variables
Upvotes: 0
Views: 1238
Reputation: 109
Adding to the previous comments, PHP Array are not the same thing as JavaScript array. There are lots of ways this can be done, one is to loop through the $timers
array in PHP and then convert that to corresponding JavaScript
Assuming the time contains array('label'=>'Today','data'=>55);
then you can use foreach
or for
to build the corresponding JavaScript array
<script type='text/javascript'>
let data=[];// this is a javascript array
<?php
$timersCount=count($timers);
for($i=0; $i<$timersCount i++){
?>
data.push({
data:<?php echo $timers[$i]['data']?>,
label:<?php echo $timers[$i]['label']?>
});
<?php
}?>
</script>
There might be typo, i just typed it but you get the idea. I am assuming you are running the script in a PHP view file.
Upvotes: 1