views:

410

answers:

2

I've got an associative array in php that I want to stick into a hidden form input so that I can later get the values in javascript. Because of quoting issues, I need to urlencode the json, or htmlentity it. Once I have the object in javascript, though, what's the easiest way to get it back to plain ol' json?

OR is there a better way to approach this issue? AJAX seems like overkill here -- I'd rather pre-populate the data on the page, rather than setting up multiple requests. I suppose I could write the php object to the page inside a php-generated script tag, but that seems a bit messy, and I'm not certain that [scripts] will be parsed in every possible situation where this might be used.

+1  A: 

If you stick the data within a field you could use decodeURIComponent to decode the value. Example:

decodeURIComponent("%5b'hello'%2c%20'world'%5d"); // ['hello', 'world']

Another approach might be to embed the JSON object in a <script> element in the PHP output. You could even go as far as to make the JSON object an argument to a function that stores it away somewhere.

<script>setupData(<?= toJSON(['hello', 'world']) ?>)</script>

When the page loads the setupData would be called with the literal ['hello', 'world'].

Bryan Kyle
giving you the nod, since it answers the question, even though I didn't turn out to need it....
sprugman
+1  A: 

Oh. I guess I should have tested first. I'm using dojo, and this Just Works:

PHP:

$arr = array('nyc'=>'big apple', 'boss'=>'big banana', 'lion'=>'big cat');
$json = htmlentities(json_encode($arr));
echo '<input type="hidden" id="myHidden" value="' . $json . '" />';

Javascript:

var raw = dojo.byId('myHidden').value;
var arr = dojo.fromJson(raw);
for (var i in arr) {
    console.log(i + " => " + arr[i]);
}

[sheepish grin]

sprugman