skip to content

PHP: Passing variables to JavaScript

PHP programmers often encounter problems when trying to dynamically generate JavaScript code. The problem is that 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 displayed in a JavaScript alert or confirmation dialog:

$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 type="text/javascript"> alert("<?PHP echo $message ?>"); </script>

but that results in invalid JavaScript code: <script type="text/javascript"> 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 type="text/javascript"> 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:

$message = preg_replace("/\r?\n/", "\\n", addslashes($message)); echo "<script type=\"text/javascript\">\n"; echo " alert(\"$message\");\n"; echo "</script>\n\n";

The output is now:

<script type="text/javascript"> 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 pass variables to JavaScript.

When trying to debug this kind of code you should always check first what's valid in JavaScript (most modern browsers have a built-in debugger for this) and only then see how it can be generated from PHP.

Note: It's not necessary to encode characters such as & and " to their HTML entities as JavaScript is a separate language from HTML and can handle them without problem.

References

< PHP


Send Feedback

Use this form to send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

CAPTCHA refresh

<- copy the digits from the image into this box

press Esc or click outside this box to close

Load Feedback Form

User Comments and Notes

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

top