Pass a PHP String to a JavaScript Variable (And Escape Newlines)

Pass a PHP string to a JavaScript variable (and escape newlines)

Expanding on someone else's answer:

<script>
var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

How to handle newlines in Javascript? (from PHP)

$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );

should replace newlines. Don't do it this way.

This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:

$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";

json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.

encoding a PHP variable with quotes and line breaks to be passed to a Javascript function (and then reverse the encoding)

I ran into problems using some of the answers proposed here, including issues with line breaks and decoding certain html entitites like /. I ended up using rawurlencode (in PHP) and decodeURIComponent (in Javascript) as matching functions to encode/decode the string so it could be passed as a JS variable. Here is working code for anybody else running into this problem.

<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress

You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
Available in Black/Nude
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<p>below is the variable doc.write'd after being rawurlencod'ed in PHP then decodeURIComponent'ed in JS:</p>
<script type="text/javascript">
<?php
echo 'document.write(decodeURIComponent("'. rawurlencode($str).'"));';
?>

How to escape new line chars in php to output into a javascript string value?

<script type="text/javascript">
var myvar = <?php echo json_encode($value); ?>;
</script>

JSON == Javascript notation == the proper encoding/escaping method for any values output to Javascript.

Display PHP string with quotes and newline in Javascript (alert)

Use json_encode to create a valid JS string:

<script>
alert(<?php echo json_encode($this->info); ?>);
</script>

How do I pass a PHP string into a Javascript function call?

echo"
<table>
<p><input type='text' id='newPostComment' value='' placeholder='WRITE YOUR COMMENT HERE...' size='35'/><input type='submit' value='UPLOAD' onclick='uploadPostComment(\"$parentID\", \"" . str_replace('"', '\"', $comment) . "\");fetchComment()'/></p>
</table>

You need to quote the fields. If your field is an integer it does not need to be quoted, if it is a string it needs to be. I quoted both because I don't know if parentID is a string id or a numeric id. Do what your application needs of course.

Update: in regards to Michael's comment about breaking if comment contains a quote. We now escape all double quotes in $comment to prevent that.

passing PHP variable in Javascript and vice versa

You need to quote the string in the onclick:

echo "<td><a href='#' onclick='disp_confirm(\"{$row->university}\")'>Delete</a></td>";

Passing string PHP to Javascript Spaces

It's got nothing to do with spaces. And you haven't given us the full code. I'm guessing that HTML is inside an echo? If so, you need to do this:

echo "<a href=\"javascript:DemoOne(".htmlspecialchars(json_encode($message)).");\" ><input type='button' value='Submit'></a>   
<div id='PageView'></div>";

i.e. json_encode any data that your pass to JavaScript. You also need to escape it for HTML since it's in an attribute as opposed to a <script> tag.


You also need to escape the query param for the URL.

I amended your code to fix the encoding issues:

  <script async  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">

function DemoOne(text) {
$('#PageView').load('test.php?text=' + encodeURIComponent(text));
}
</script>


<?php
$message="hello";

echo " <a href=\"javascript:DemoOne(".htmlspecialchars(json_encode($message)).");\" ><input class='btn' type='button' value='Test'></a>
<div id='PageView'></div>";

Alternatively, let jQuery do the escaping:

function DemoOne(text) {
$('#PageView').load('test.php', {text:text});
}


Related Topics



Leave a reply



Submit