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

4
  • print here your console.log( arrJS ); Commented May 3, 2015 at 9:11
  • try console.log( json_decode(arrJS['123']) ); Commented May 3, 2015 at 9:13
  • You can use var obj= jQuery.parseJSON(arrJs); and access as object with -> exmp - obj->123; Commented May 3, 2015 at 9:15
  • anant kumar singh, json_decode is php func actualy Commented May 3, 2015 at 9:25

2 Answers 2

0

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

var parsed = JSON.parse(arrJS);

Wish it helps!

Sign up to request clarification or add additional context in comments.

Comments

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>

3 Comments

right, i dont use any quotes actually. here was the typing mistake
cant)) low reputation)) do you know what big different between JSON.parse and jQuery.parseJSON?
you can see the difference here. stackoverflow.com/questions/10362277/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.