What is the correct format to PHP echo a JavaScript Alert which uses PHP variables? [duplicate]

StackOverflow https://stackoverflow.com/questions/23522167

  •  17-07-2023
  •  | 
  •  

Domanda

I used

<?php     
$myArr =  "foo" => "bar",
          "bar" => "foo",; 
$myVar =  "Word!";

echo '<script type="text/javascript">alert("The $myVar is print_r($myArr) ");</script>';
?>

To show an alert on the page. I take it is wrong, whats the right way of doing so?

È stato utile?

Soluzione

You should always JSON-encode data used in the context of JavaScript. This makes the data safe for use, so you don't have to worry about injection or escaping.

<script>
  <?php 
      $myArr = array(1, 2, 3, 4, 5);
      $myVar = 'Word!';
      echo 'var myArr = ', json_encode($myArr), ';'; // var myArray = [1, 2, 3, 4, 5];
      echo 'var myVar = ', json_encode($myVar), ';'; // var myVar = "Word!";
  ?>

  console.log(myArr);
</script>

Altri suggerimenti

Like sean9999's answer, this one avoids polluting the global namespace, but in a more straightforward way, without PHP short tags.

<?php $bar = "qux"; ?>

<script>
;(function () {
    var foo = <?php echo json_encode($bar); ?>;
    alert(foo);
}());
</script>

Here's how you might do it in a way that limits potential for polluting the global namespace

<?php
$myArr =  ["foo" => "bar", "bar" => "foo"]; 
$myVar =  "Word!";
?>
<script>
;(function(myArr,myVar){
  "use strict";
  alert( myVar + ' is ' + JSON.stringify(myArr) );
})(<?= json_encode($myArr) ?>,'<?= $myVar ?>');
</script>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top