Is it possible to use PHP a specific variable in javascript?

Is it possible to use in javascript a variable that was defined in earlier PHP code?

For example (in the PHP file of the page template):

<?php
$arr = array(-34, 150);
?>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
...
var latlng = new google.maps.LatLng($arr);
...
}
</script>
+3
source share
3 answers

Even better, use wp_localize_script () to pass variables from PHP to javascript:

wp_enqueue_script( 'my-script', '/path/to/my-script.js' );

$loc_variables = array(
    'lat' => $latitude,
    'lon' => $longitude
    );

wp_localize_script( 'my-script', 'location', $loc_variables );

And then in your my- script.js you can access these variables as location.latwell location.lon.

+7
source

No, but you can do it js var ...

<script type="text/javascript">
var myArray = new Array(<?php echo $myArrayVals; ?>);
</script>
+2
source

, JS, PHP json_encode.

For example, if you have an array in PHP

<?php
 $cow=array('bat'=>false,'fob'=>'widget');

What do you want in js then you could

<script>
  var cow=<?php echo json_encode($cow);?>; 
  // prints {"bat":false,"fob":"widget"}
  console.log(cow.fob);//'widget' of course

json_encode also takes care of quoting strings. Of course, not all PHP values ​​are json_encodable - objects with methods cannot be expressed as javascript values, but that doesn't seem like you're worried about this.

0
source

All Articles