Chartjs-Chart.js isn't able to read elements from php as label

2👍

Since the output is not an integer, but a time (“16:44:04”), you can not place it inside an array without quotes.

$res4 .= '"'.$chronos[$x] . '", ';

As a more general approach, I don’t suggest you to use string concatenation but PHP arrays and then implode them. This avoids having to trim the last comma.

$res1 = [];
$res2 = [];
$res3 = [];
$res4 = [];
$len1 = count($temp);
$len2 = count($humi);
$len3 = count($id);
// input elements into variables
for($x = $len1 - 10; $x < $len1; $x++) {
    $res1[] = $temp[$x];
}
for($x = $len2 - 10; $x < $len2; $x++) {
    $res2[] = $humi[$x];
}
for($x = $len3 - 10; $x < $len3; $x++) {
    $res3[] = $id[$x];
}
//set timezone
date_default_timezone_set("Asia/Manila");
// set time
$date = date("H:i:s");
$time = strtotime($date);
$time = $time - 20;
// iterate time into array
for($y = 0; $y < 10; $y++) {
    $time = $time + 2;
    $date = date("H:i:s", $time);
    array_push($chronos, $date);
}
// iterate timesinto variables
for($x = 0; $x < 10; $x++) {
    $res4[] = '"'.$chronos[$x].'"';
}
?>

And then

<script>
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [<?php echo implode(",", $res4); ?>],
            datasets: [{
                label: 'Temperature',
                fill: false,
                data: [<?php echo implode(",", $res1); ?>],
                borderColor: ['rgba(255,99,132,1)'],
                borderWidth: 1,
                pointBackgroundColor: [...]
            }, {
                label: 'Humidity',
                fill: false,
                data: [<?php echo implode(",", $res2); ?>],
                borderColor: ['rgba(54,162,235,1)'],
                borderWidth: 1,
                pointBackgroundColor: [...]
            }]
        }
    });
</script>

0👍

Your $res4 is an array of string, not date, so labels: [<?php echo $res4; ?>], will be like:

labels: [10:00:01, 10:00:02, 10:00:03, ...]

Javascript cannot read it because SyntaxError. You may need to put $res4 into an temporary array, then parse it to time before assign it to labels.
But before that, you need to quote your $chronos[$x] like this:

...
for($y = 0; $y < 10; $y++) {
  $time = $time + 2;
  $date = date("H:i:s", $time);
  array_push($chronos, $date);
}
// iterate timesinto variables
for($x = 0; $x < 10; $x++) {
  $res4 .= '"$chronos[$x]"' . ', ';
}
// trim last comma
$res1 = rtrim($res1, ', ');
$res2 = rtrim($res2, ', ');
...

And then in your front end

var temp = [<?php echo $res4 ?>];
// parse your time here

Hope this help.

Leave a comment