2

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() );

littlewolf
  • 173
  • 1
  • 2
  • 19

2 Answers2

0

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

var parsed = JSON.parse(arrJS);

Wish it helps!

Kevin
  • 149
  • 10
0

it is just because json_encode convert array with double quotes "

when using double quotes " with value result will be

enter image description here

so change value="<?php echo json_encode($arr); ?>" to value='<?php echo json_encode($arr); ?>'

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

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

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        $(function (){
          var arrJS = $("#arr").val();
          arrJS = JSON.parse(arrJS);
          console.log( arrJS );         
          console.log( arrJS['123'] );  
        });
    </script>
Noman
  • 4,088
  • 1
  • 21
  • 36