The best way to do this is to encode the values using json_encode
. Here is a simple example:
<?php
$name = "Jason's Bakery";
?>
<script>
var name = <?php echo json_encode($name); ?>;
DoSomethingWithName(name);
</script>
This can be used for integers, strings, and other values. Keep in mind that it will add quotes as needed, so you need to assemble and encode a "whole value at once". In your example of using the URLs, you need to use the PHP urlencode()
function to encode them FIRST, and then pass it through json_encode
to convert to a javascript value. And if you are placing that inside of an HTML attribute, like onclick
, you need to further pass it through htmlspecialchars(..., ENT_QUOTES)
and then place it in double quotes.
http://php.net/manual/en/function.json-encode.php
So for example, you need to build a URL in PHP and then use it in javascript...
<?php
$name = "Jason's \"Awesome\" Bakery";
$url = "http://site.com/page.php?name=" . urlencode($name);
?>
<script>
var name = <?php echo json_encode($name); ?>;
DoSomethingWithName(name);
</script>
<input type="button" onclick="<?php echo htmlspecialchars('window.location = ' . json_encode($url) . ';', ENT_QUOTES); ?>" value="Click Me" />
Which results in something like this:
<script>
var name = "Jason's \"Awesome\" Bakery";
DoSomethingWithName(name);
</script>
<input type="button" onclick="window.location = "http:\/\/site.com\/page.php?name=Jason%27s+%22Awesome%22+Bakery";" value="Click Me" />
Needless to say, you do not want to do without these:
http://php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.urlencode.php
http://www.php.net/manual/en/function.htmlspecialchars.php