简体   繁体   中英

Passing an Array from PHP to Javascript

I'm trying to pass on a PHP array to then use the array in JavaScript.

The PHP code I'm using is as follows:

<?php

$link = mysqli_connect("localhost", "root", "password", "database");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    $query = "SELECT * FROM Employees";

    if ($result = mysqli_query($link, $query)) {

        /* fetch associative array */
        while ($row = mysqli_fetch_assoc($result)) {

            $data[] = $row;
        }
        print_r($row);
        /* free result set */
        mysqli_free_result($result);
    }
    /* close connection */
    mysqli_close($link);

//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($data);
?>

JavaScript:

<script> 
    var array = <?php echo $data; ?>; 
    console.log(array); 
</script>

The data array in PHP doesn't seem to get passed on to the Javascript var array . When looking at the console on firebug the following error messages are displayed:

Notice - Array to string conversion.

I'd really appreciate any help as to why this error is occurring.

Maybe because you are echo'ing the array instead of the json encoded string.

Use this

<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>

I believe it should be:

<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>

You're using json_encode in $data but you're not using that variable in your code. Could that be it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM