<script> var myvar = "<?php echo $myVarValue;?>"; </script>
Then some one will suggest that
<script> var myvar = <?= json_encode($myVarValue); ?>; </script>
My solution is to add JSON_HEX_APOS to the json_encode call to escape single quote.
<script> var myvar = <?= json_encode($myVarValue,JSON_HEX_APOS); ?>; </script>
The bitmask options parameter was added to json_encode since 5.3.0.
Added on 30th Nov 2010
If your php is still on older version than 5.3 then this code will work without using json_encode.
<script> var myvar = <?= '"'.mysql_escape_string($myVarValue).'"'; ?>; </script>
Why use mysql_escape_string and not addslashes?
Because mysql_escape_string will escape \r\n while addslashes only escape single and double quotes.