This question already has an answer here:
What is the easiest way to encode a PHP string for output to a JavaScript variable?
I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.
Normally, I would just construct my JavaScript in a PHP file, à la:
<script>
var myvar = "<?php echo $myVarValue;?>";
</script>
However, this doesn't work when $myVarValue
contains quotes or newlines.
I'm not sure if this is bad practice or no, but my team and I have been using a mixed html, JS, and php solution. We start with the PHP string we want to pull into a JS variable, lets call it:
Next we use in-page hidden form elements, and have their value set as the string:
Then its a simple matter of defining a JS var through document.getElementById:
Now you can use the JS variable "moonUnitAlpha" anywhere you want to grab that PHP string value. This seems to work really well for us. We'll see if it holds up to heavy use.
Don’t. Use Ajax, put it in
data-*
attributes in your HTML, or something else meaningful. Using inline scripts makes your pages bigger, and could be insecure or still allow users to ruin layout, unless…… you make a safer function: