Skip to content Skip to sidebar Skip to footer

Php Variable (with Quotes) In Javascript

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 ac

Solution 1:

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

<?php$a1 = "Here is the \"best\" apple around"; 
?>var str = <?phpecho 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_encodeprevents script-injection, with the default options.

Solution 2:

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

<scripttype="text/javascript">var str = "<?phpecho 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); ?>;

Solution 3:

use htmlspecialchars to convert $a1

$a1= htmlspecialchars("Here is the \"best\" apple around"); 

Post a Comment for "Php Variable (with Quotes) In Javascript"