Jump to content

json_encode hell!


Thingfish47

Recommended Posts

In php  I have extracted 20 items from the db, and can display them fine. I drop out of php into javascript and execute the following line of code (straight from examples...)

 

var kArray = <?php echo json_encode($Keys); ?>;

 

I have also tried 

 

var kArray = <?php echo json_encode($Keys,JSON_FORCE_OBJECT); ?>;

 

kArray.length is undefined, and are all entries.

 

Do I need to install more software for this to work?

 

I have PHP 7

Link to comment
Share on other sites

$Keys is an array containing 20 integers.  It all debugs out to console.log correctly.  There are NO security issues with this, it will never get out of the lan, and runs on my personal development PC, but I'm happy to learn. All I really want to do is get hold of the data as quickly and easily as possible.  This is not my main area of expertise, and almost certainly never will be.

Link to comment
Share on other sites

You can literally copy and paste the example code from the above thread:

<?php

header('Content-Type: text/html; charset=UTF-8');



// test data
$keys = [3, 42, 99];

?>
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>JSON</title>
        <style>
            .hidden {
                display: none;
            }
        </style>
    </head>
    <body>
        <div id="my-data" class="hidden"><?= htmlspecialchars(json_encode($keys), ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8'); ?></div>
        <script>
            var kArray  = JSON.parse(document.getElementById('my-data').innerHTML);

            alert('Array content: ' + kArray);
        </script>
    </body>
</html>

Edited by Jacques1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.