Reputation: 3195
I am attempting to pass some text from my PHP code to Javascript through HTML. It works fine unless the text has a single quote. Here is how I am doing it:
<script>
var t = '<?php echo json_encode(an array containing text "he's here");?>';
</script>
I tried changing the single quotes around the php echo to double quotes. but, of course, JSON uses double quotes, so I had the same problem.
Upvotes: 0
Views: 2176
Reputation: 902
You need to use the json_encode constant JSON_HEX_APOS as the second parameter which will convert all single quotes ' to \u0027. :
var t = <?php echo json_encode($data,JSON_HEX_APOS);?>;
Then use encode () and decode () javascript functions to convert the text from each array entry back to readable text like this example http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_unescape
Upvotes: 3
Reputation: 1392
Remove single quote around the php
<script type="text/javascript">
var t = <?php echo json_encode(array("text"=>"he's here"));?>;
</script>
it will create, t
variable as
Object {text: "he's here"}
Upvotes: 1