0

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: enter image description here

If I simple echo the JSON out to display on the webpage that works fine without any errors. What am I doing wrong?

4
  • 1
    $test is not the encoded json Commented Apr 22, 2014 at 14:13
  • Are you sure you're assigning $test the JSON encoded value? Also what are the brackets for? Commented Apr 22, 2014 at 14:14
  • 2
    looks like html to me, not JSON Commented Apr 22, 2014 at 14:15
  • it's some sort of stack trace for maybe like undefined variable Commented Apr 22, 2014 at 14:15

3 Answers 3

4

Do it like this:

$test = json_encode($test, true);

json_encode doesn't change the variable in place.

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

Comments

1

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.

Comments

0

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.

Comments

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.