PHP: Passing variables to JavaScript
PHP programmers often encounter problems when trying to dynamically generate JavaScript code. Some characters need to be escaped in JavaScript, and also in PHP. This double-up can be hard to come to grips with.
Escaping Quotes and Line Breaks
Suppose you start with a PHP variable that needs to be inserting into a JavaScript code block. In this situation your variables will normally be enclosed in dbouble-quotes, so we don't need to worry about strings containing single quotes.
$message = "a short piece of text
spanning more than one line
and containing \"double\" & 'single' quotes";
The obvious way to turn this into an alert is:
<script>
alert("<?PHP echo $message ?>");
</script>
but this approach results in invalid JavaScript code:
<script>
alert("a short piece of text
spanning more than one line
and containing "double" & 'single' quotes");
</script>
There are two problems. Firstly, having line breaks inside a JavaScript variable is not an option. They'll need to be replaced with \n (character representation of a line break). Secondly, the double quotes inside the text conflict with the outer quotes of the alert call.
Learning from our mistakes, here's some code that actually works:
<script>
alert("<?PHP echo preg_replace("/\r?\n/", "\\n", addslashes($message)); ?>");
</script>
The above code relies on PHP being embedded within HTML code. If you're outputting the entire page from PHP then you need to go a step further:
<?PHP
$message = preg_replace("/\r?\n/", "\\n", addslashes($orig_message));
echo "<script>\n";
echo " alert(\"{$message}\");\n";
echo "</script>\n\n";
The output is now:
<script>
alert("a short piece of text\nspanning more than one line\nand containing \"double\" & \'single\' quotes");
</script>
The same approach can be applied in pretty much any situation where PHP needs to insert variables into a JavaScript code block.
It's not necessary to encode characters such as & and " to their HTML entities inside a JavaScript <script> block. JavaScript in this context is kept separate from the HTML and can handle them without problem.
Working with inline JavaScript
Inline JavaScript presents a particular problem as the code itself is usually enclosed in double quotes, with the contained JavaScript then forced to used single quotes by default:
<button onclick="alert('...');">Click Me</button>
At first glance, the approach from above should work here as well:
<button onclick="alert('a short piece of text\nspanning more than one line\nand containing \"double\" & \'single\' quotes');"></button>
But what you will see in practice is a syntax error:
SyntaxError: Unexpected EOF
The problem is that inline JavaScript is actually part of the HTML markup so certain characters, namely quotes, ampersands and the less/greater than signs, need to be escaped HTML-style, as follows:
<button onclick="alert('a short piece of text\nspanning more than one line\nand containing "double" & \'single\' quotes');"></button>
Which we can achieve in PHP using htmlspecialchars:
<button onclick="alert('<?PHP
echo preg_replace("/\r?\n/", "\\n", addslashes(htmlspecialchars($message)));
?>');;">Click Me</button>
PHP 8.1 breaks things
As a final twist, as of PHP version 8.1.0 single quotes are no longer escapes as \' as before. Now instead they appear as ' which breaks our code as described here.
Fortunately, there is a simpl-ish patch:
<button onclick="alert('<?PHP
echo preg_replace("/\r?\n/", "\\n", addslashes(htmlspecialchars($message, ENT_COMPAT)));
?>');;">Click Me</button>
You can test this in your browser by clicking the button:
Final checks
When trying to debug this kind of code you should always check first what's valid in JavaScript, and most modern browsers have a built-in debugger for this purple. Only then see how the working code can be generated from PHP.
References
Related Articles - Text Manipulation
- HTML Forcing INPUT text to uppercase
- JavaScript HTML content that expands on click
- JavaScript Collapsible containers with rotation support
- PHP Truncating Text
- PHP Word Wrapping
- PHP Passing variables to JavaScript
- PHP What happened with htmlspecialchars?
RasKalad 9 August, 2012
I wanna pass "$name" into javascript, AJAX to be precise, so that that variable can b passed to the server and database, returning the corresponding values.
I need a diferent code don't I?
denson 1 November, 2011
You totally rock...I spent two days trying to figure out how to get html saved in a mysql database into a javascript. This did the trick!
Gabo Lugo 21 July, 2011
@PCheese
That's true! Very useful when generating javacript code on php.
Thanks for your hint
gaurav 24 June, 2011
tahanx a lot for your superb article.......
solution posted by PCheese is also working.......
PCheese 18 February, 2011
Try json_encode instead; that seems to handle all the tricky bits including quotes and newlines. Example:
echo "<script>alert(" . json_encode($message) . ");</script>"
ravi 24 November, 2010
Thanks a ton... Had been scratching my head to solve the similar issue while coding. Your solution worked like a MAGIC. Thanks once again.
Rob Staveley 29 July, 2010
Just wanted to say thank you - figuring that out myself would have made me late for lunch.
tajaf 2 March, 2010
thank you. But what if I want to pass a javascript variable to a php function in the same page?
To call a PHP function without reloading the page you need to either use Ajax or load a PHP script by using an IMG, IFRAME or similar, with $_GET parameters.
Raymond 17 February, 2010
OH LORD! Been trying to break this code for over 4 hours then I find this piece of gold mine! thx a lot!
ujjaldey 7 February, 2010
Thanks a ton... Had been scratching my head to solve the similar issue while coding. Your solution worked like a MAGIC. Thanks once again.
NĂcolas Iensen 9 May, 2009
Funny there is no native PHP function to do that job.
Nice article guys!
Karolis 16 October, 2008
Can I be sure that these characters are the only characters needed to be escaped? Are there any characters that can led into wrong JavaScript code (even though theoretically)? What about UTF-8?
Thank you very much!
cami 24 June, 2008
What if you don't want to alert it, just to use it as a regular javascript variable?
'alert()' is just a function like any other. There's no difference in approach if you want to use a different function or just define a variable in JavaScript. It's the escaping of the $message component as demonstrated in this article that's important in each case.
Brian 9 September, 2007
Wow, thank you so much. I had worked all day on a roundabout way to accomplish this when your script works perfectly. I should google things more specifically before I dive into time consuming solutions.
tison 5 September, 2006
just wanted to thank you guys for this article. I have been seriously stuck on that for about 2 hours now. thanks again,
tison