0

I am trying to import three arrays from php into js using json_encode

Here is the code:

<?php
    $query2 = "SELECT * FROM all_data";

    $result2 = $conn->query($query2);

    $bu = [];
    $rank = [];
    $id = [];

    if ($result2->num_rows > 0) {

        while($row2 = $result2->fetch_assoc()) {
            $bu[] = $row2["bu"];
            $rank[] = $row2["rank"];
            $id[] = $row2["id"];
            echo "<tr class='dn' id='u-" . $row2["rank"] . "'>";
            echo "<td>" . $row2["rank"] . "</td>";
            echo "<td>" . $row2["bu"] . "</td>";
            echo "<td>" . $row2["tokens"] . "</td>";
            echo "</tr>";
        }

    }


    ?>

    var users = <?php echo json_encode($bu); ?>;
    var ranks = <?php echo json_encode($rank); ?>;
    var identifier = <?php echo json_encode($id); ?>;

Problem is, the arrays ranks and identifier are getting imported correctly, but users is not. This script was working the last few times I used it. Recently however, I changed the table all_data, by dropping it and then importing it from csv again. However the charset was utf8 when I imported, so I don't understand what the problem might be here.

Even if I am just doing <?php echo json_encode($bu) ?> it is not working. However <?php print_r($bu) ?> shows me that the array is not actually empty and it actually contains the query results.

Yuki.kuroshita
  • 759
  • 9
  • 29

2 Answers2

2

json_encode turns the array into a string; if you want to have access to the array again in Javascript, parse the string back to an array again, such as:

var users = JSON.parse('<?php echo json_encode($bu); ?>');

But it's quite bad practice to create JS on the fly like this - if you want the script to have information served from your PHP, either insert the object into a element which gets parsed by the Javascript, or use data- attributes.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Even if I don't want to use it in javascript, at least json_encode should work right? Problem is json_encode is working for everything except $bu – Yuki.kuroshita Mar 26 '18 at 23:51
0

As @kip points out in the comments, the most likely cause of the failure is the conversion of a unicode character, or other special characters that is causing the json_encode to fail to encode the array.

Most likely, you will need to use one of the json_encode predefined constants such as @kip recommended:
json_encode($bu, JSON_UNESCAPED_UNICODE);

I would actually take this a step further and use:
json_encode($bu, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR)

Finally, since you know you are getting a json_encode error of some kind, after running your line
var users = < ? php echo json_encode($bu); ?>;

You can add the line:
json_last_error()

This will tell you exactly what the problem is, and should allow you to adjust the parameters of the json_encode to work with your $bu array.

Bryan Teague
  • 41
  • 1
  • 4