Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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>';
share|improve this question

1 Answer

up vote 4 down vote accepted

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>
share|improve this answer
BIG thanks for this one. Couldn't figure it out in past hours. – Primož 'c0dehunter' Kralj May 27 '12 at 21:46
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. – Corbin May 27 '12 at 21:49
Where is this console.log? Edit: do you mean Firebug? I've never used it before and maybe I should start :) – Primož 'c0dehunter' Kralj May 27 '12 at 21:50
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. – Corbin May 27 '12 at 21:52
Thanks, great piece of advice. – Primož 'c0dehunter' Kralj May 27 '12 at 21:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.