2

I have an array in PHP, which I pack to JSON object with _json_encode(..)_ . Then I send it to JS function as parameter. When I want to parse the object in Javascript with eval(..) nothing happens (there is an error behind the curtains I guess). What could be wrong?
Code:

<script type="text/javascript">
    function testFun(inArr) {
      var obj=eval('('+inArr+')');
      alert(obj.m); //alert(obj) also doesnt work
    }
</script>  


//PHP
$spola_array = array('m' => 1, 'z' => 2);
$json_obj=json_encode($spola_array);
echo '<script type="text/javascript">testFun('.$json_obj.');</script>';

1 Answer 1

5

It's already parsed since you're outputting it as an object literal and not a string. That will look like:

<script type="text/javascript">testFun({m: 1, z: 2});</script>

So in your function, it's just:

alert(inArr.m) //1

You would only need to parse it if it were a string:

<script type="text/javascript">testFun('{m: 1, z: 2}');</script>
Sign up to request clarification or add additional context in comments.

5 Comments

BIG thanks for this one. Couldn't figure it out in past hours.
No problem. Sometimes it can help to debug things like this with console.log by the way. It typically provides a better formatted output than alerts.
Where is this console.log? Edit: do you mean Firebug? I've never used it before and maybe I should start :)
It's just a function the dev tools of Chrome and IE expose, and a function exposed by Firebug in Firefox. You just use it like console.log("test!"); or console.log(someVar); It's not meant to be used in production code. It's just a slightly more useful way of doing alert(someVar). It typically includes a little bit of information about the type of variable, and in the case of object literals, it will show that they are objects and show which keys are defined.
Thanks, great piece of advice.

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.