Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using a PHP defined variable in javascript possible? [duplicate]

Tags:

javascript

php

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

For example (in a page template PHP file):

<?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>

2 Answers

Even better, use wp_localize_script() to pass your 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 those variables as location.lat and location.lon.

like image 130
goldenapples Avatar answered Jul 03 '26 02:07

goldenapples


No, but you can make it a js var...

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!