Pass PHP String To Javascript Variable
When you try to pass a php string to a javascript varaible like
<script> var myvar = "<?php echo $myVarValue;?>"; </script>
If there is any special characters like quote or new line, it is very likely javascript will be broken with an error message like:unterminated string literal
Then some one will suggest that
<script> var myvar = <?= json_encode($myVarValue); ?>; </script>
This is still not good enough, as single quote still not escaped, and javascript will be terminated earlier than it should be.
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.

I’ve always liked:
var my_variable = unescape(“”);
Thanks a lot, this has saved me several hours of coding!