Pass PHP String To Javascript Variable

When you try to pass a php string to a javascript varaible like

  var myvar = "<?php echo $myVarValue;?>";

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

  var myvar = <?= json_encode($myVarValue); ?>;

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.

  var myvar = <?= json_encode($myVarValue,JSON_HEX_APOS); ?>;

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.

  var myvar = <?= '"'.mysql_escape_string($myVarValue).'"'; ?>;

Why use mysql_escape_string and not addslashes?
Because mysql_escape_string will escape \r\n while addslashes only escape single and double quotes.

This entry was posted on Friday, November 19th, 2010 at 3:56 am and is filed under Javascript, PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Pass PHP String To Javascript Variable”

  1. Bash says:

    I’ve always liked:

    var my_variable = unescape(“”);

  2. Danson says:

    Thanks a lot, this has saved me several hours of coding!

Leave a Reply