Thursday, April 18, 2013

Passing variables to JavaScript usin php

 

 

 http://blog.outsourcing-partners.com/wp-content/uploads/2012/11/javascript.jpg

 

1. 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.

0 comments: