This is all in the same script. I know the difference between ajax and serverside code. I have php interwoven in this javascript script as follows:
<script>
<?php
$json_string = json_encode(array("agent_table" => "<span style='float: left;'></span>"));
?>
var response = $.parseJSON('<?php echo $json_string; ?>');
</script>
But parseJson is complaining of an error. The error disappears when I remove the styling from the span.
The error is ‘Unexpected identifier’. This is in Chrome.
You have
'characters in your data. These will continue to be represented as literal'characters in the JSON.You are embedding your JSON directly into a JavaScript string, and that string is delimited by
'characters. The first'that appears as data in the JSON will terminate the JS string.This is a general problem when embedding on data format in another. You are embedding JSON in JavaScript in HTML.
Your options:
'in the JSON with\'(so they mean “Apostrophe” instead of “End of JS string”)The latter option is the sane one (so long as your goal doesn’t involve proving that PHP can generate valid JSON).
You don’t need to worry about further escaping for inserting into the HTML because the only sequence you need to worry about (inside a script element) is
</script>and PHP’sjson_encodewill output<\/script>for that anyway.