tjarles tjarles - 1 year ago 66
JSON Question

JSON containing single quote causes syntaxerror

So I have data that needs to be fetched through php. This data should then be saved to a javascript variable by in the .php file echoing the value:

$json = json_encode($requirements);
echo "<script>
var myvar = '<?php echo $json; ?>';

The data contains a single quote which gives syntax error in Chrome:

Uncaught SyntaxError: Unexpected identifier

The page source look something like by the error:

var myvar = '<?php echo {"data":{"data":{"1":{"description":"Don' t}}}}; ?>';

where the entire string up until ""Don'" is in red.

What is the right way of keeping json_encode from failing (apart from calling the data directly to js)?

Answer Source

You need to escape ' chars then, for example by using backslash \:


Or as you are using php you can use addslashes function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download