How would i go about printing my php array in my javascript code? i tried different things but it would only print out the last number.
In the code below where i wrote 'Print the array here', is where i would like to print my php array (if it wasnt already obvious).
PHP example:
$phpArray = array('bunch of numbers');
Javascript example:
let time_chart = new Chart(myChart, {
type:'line',
data:{
labels:['Week 1', 'Week 2', 'Week 3', 'Week 4'],
datasets:[{
label:'Minutes',
data:[
'Print the array here'
],
This code should not be in a separate .js
file. It should be inside php file. Then only you can use PHP tags in your JS code.
If above is the case then,
let time_chart = new Chart(myChart, {
type:'line',
data:{
labels:['Week 1', 'Week 2', 'Week 3', 'Week 4'],
datasets:[{
label:'Minutes',
data: <?php echo json_encode($phpArray);?>,
if your file is php
data:[<?php echo json_encode($phpArray) ?>],
OR
data:<?php echo json_encode($phpArray) ?>,
I'd avoid mixing PHP and JavaScript - they're separate languages for a reason. Best way I recommend is using hidden inputs with data-tags:
html:
<input type="hidden" id="my-array" data-value="<?php echo json_encode($myArray); ?>" />
jquery:
var array = $('#my-array').data('value');
// ...
data: array
// ...