1

I am trying to access a PHP variable in JavaScript. I've escaped quotes in the PHP variable and the JavaScript won't pick it up. Without changing the $a1 php variable, how can I access it in JavaScript?

<?php

$a1 = "Here is the \"best\" apple around";    //<-- doesn't work in javascript...
$a2 = "Here is the best apple around";        //<--works fine in javascript...

?>

JavaScript:

<script type="text/javascript">

var str = "<?php echo $a1; ?>";
alert(str);

</script>
Bzyzz
  • 173
  • 5
  • 15

3 Answers3

4

Use json_encode for simplicity and consistency. See the ideone example.

<?php
    $a1 = "Here is the \"best\" apple around"; 
?>
var str = <?php echo json_encode($a1); ?>;

Result:

var str = "Here is the \"best\" apple around";    

Don't supply quotes in the JavaScript itself, as those come from the encoded result as required.

Advantages:

  • Correct. The result always represents a valid JavaScript literal (or object/array) expression.
  • Simple. No need to worry about quotes in JavaScript when dealing with string values.
  • Consistent. The same approach works for many values - e.g. arrays (indexed, keyed, and complex), numbers, booleans, NULL - and preserves more type information.
  • Secure. Using json_encode prevents script-injection, with the default options.
Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • 1
    You say the output of `json_encode` is invalid, is that because it is a string rather than an object or an array? They changed that in the [latest version of the JSON spec](http://tools.ietf.org/html/rfc7159) so that a json text can be any json value (surrounded by any amount of whitespace). – Quentin Aug 16 '14 at 22:32
  • It's just so that parsers don't fall over when you have a new line at the end of the file / indentation / etc. – Quentin Aug 16 '14 at 22:34
  • @Quentin Thanks again for the update - and yes, the original aside was because I was not aware of spec changes. It's nice to see that that JSON now encompasses primitive values at the top-level. – user2864740 Aug 16 '14 at 22:38
-1

Depending on where you want to output your "str" ( in an alert or on a html page ) i would take different commands.

<script type="text/javascript">

var str = "<?php echo addslashes($a1); ?>";
alert(str);

</script>

If you would like to add it as a new DOM element i would prefer htmlspecialchars or htmlentities .

As an alternative:

var str = <?php echo json_encode($a1, JSON_UNESCAPED_UNICODE); ?>;

jvecsei
  • 1,936
  • 2
  • 17
  • 24
-2

use htmlspecialchars to convert $a1

$a1 = htmlspecialchars("Here is the \"best\" apple around"); 
Joris Ros
  • 389
  • 2
  • 6