-3

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'
                ],
simplex
  • 3
  • 5
  • Don't create Javascript on the fly like that - to send data from the server to the client, use `data-` attributes, `application/json`, or a network request. – CertainPerformance Apr 27 '18 at 07:45
  • you need to enclose it in PHP tags. – hungrykoala Apr 27 '18 at 07:46
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – miken32 Apr 27 '18 at 16:29

3 Answers3

0

if your file is php

data:[<?php echo json_encode($phpArray) ?>],

OR

data:<?php echo json_encode($phpArray) ?>,
Maninderpreet Singh
  • 2,569
  • 2
  • 17
  • 31
0

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);?>,
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
0

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
// ...
treyBake
  • 6,440
  • 6
  • 26
  • 57