Hacker
Hacker

Reputation: 7906

purpose of eval in this case

I am studying a custom framework. I found a code like

<script type="text/javascript"> 
<?php
    echo "ABC.Variables.Objects = eval('(" . $Objects . ")');";
?>
</script>

and in see source i saw code like

ABC.Variables.Objects = eval('({"success":true,"results":11})');

what was the main purpose of using EVAL in this case? Is is working on client side of server side?

Upvotes: 0

Views: 75

Answers (3)

xdazz
xdazz

Reputation: 160883

eval here is use to turn the json format string to a javascript object. The right way to do this is to use JSON.parse(str) or some json parse functions for old browsers.

But you don't need to use eval in such case, even JSON.parse() is not necessary.

You just need to do:

<script type="text/javascript">
  // of course $Objects needs to be a valid json string, eg the result of json_encode 
  ABC.Variables.Objects = <?php echo $Objects ?>;
</script>

And in the source you should see:

ABC.Variables.Objects = {"success":true,"results":11};

No eval is needed.

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270677

The PHP has output JavaScript code to be executed by the client browser. In the JavaScript (not the PHP), eval() is called to parse a JSON string which was originally stored in a PHP variable $Objects into a JavaScript object.

Rather than eval(), it really ought to be calling JSON.parse().

Would have been better:

echo "ABC.Variables.Objects = JSON.parse('" . $Objects . "');";

Upvotes: 1

Gunah Gaar
Gunah Gaar

Reputation: 535

Here, the eval function converts a json string into json object.

Upvotes: 0

Related Questions