Vitalik Zenin Vitalik Zenin - 4 months ago 10
PHP Question

php associative array to javascript - doesn't work

I'm trying and trying. I think it has worked so far, but now it doesn't..

<?php
$arr['123'] = 'QWE123';
$arr['124'] = 'QWE124';
?>

<input id="arr" value=<?php echo json_encode($arr); ?> hidden>

<script>
$(function (){
var arrJS = $("#arr").val();
console.log( arrJS ); // looks fine {"123":"QWEQWE123","124":"QWEQWE124"}
console.log( arrJS['123'] ); // undefined !!!
});
</script>


p.s. to object didn't help.
arrJS = Object( $("#arr").val() );

Answer

You have to parse the json. You may do it like this:

var parsed = JSON.parse(arrJS);

Wish it helps!