Reputation: 6170
I'm not sure why this isn't working, as a lot of the examples on the internet suggest doing it this way. Anyway, I have a SQL result that I've converted to JSON and now I'm trying to use that with Javascript.
json_encode($test, true); ?>
<script type="text/javascript">
var obj = (<?php echo $test; ?>);
alert(obj.toSource());
</script>
This does not work and Chrome gives me an error of "illegal character" and the Javascript variable somehow displays some x-debug HTML from the PHP server:
If I simple echo the JSON out to display on the webpage that works fine without any errors. What am I doing wrong?
Upvotes: 0
Views: 73
Reputation: 24661
You're doing a couple of things wrong here..
json_encode($test, true);
I think you're probably thinking of json_decode
, but the second parameter to json_encode
is supposed to be a bitmask of options. Passing true
here is probably wrong.
@ElmoVanKielmo is also correct, the variable doesn't change because you call a function, you must reassign the variable to the return value.
Upvotes: 1
Reputation: 2150
You got hmtl that looks line an xdebug error/notice message. Fix that before you proceed! (You cut out the part where the message is put).
Additionally you do not encode $test correctly. json_encode returns the changed value and does not modify it by reference.
Upvotes: 0
Reputation: 11290
Do it like this:
$test = json_encode($test, true);
json_encode
doesn't change the variable in place.
Upvotes: 4