3

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>
  • This question should be posted on stackoverflow since it's not Wordpress dependent – Boris Delormas May 04 '11 at 15:26
  • @Kaaviar - I didn't realize that. Will do next time. –  May 04 '11 at 15:40
  • 1
    Duplicate of [Get variable from PHP to JavaScript](http://stackoverflow.com/questions/415868/get-variable-from-php-to-javascript), ["How to access PHP variables in JavaScript or jQuery rather than "](http://stackoverflow.com/questions/1808108/how-to-access-php-variables-in-javascript-or-jquery-rather-than-php-echo-varia), ["Access PHP variable in JavaScript"](http://stackoverflow.com/questions/4287357/access-php-variable-in-javascript) – outis May 04 '11 at 20:01

3 Answers3

7

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.

goldenapples
  • 386
  • 1
  • 15
  • nice, didn't know about that one. –  May 04 '11 at 19:00
  • @goldenapples, Thanks. Can you say why is this way better? –  May 04 '11 at 19:30
  • @Ash - This method does essentially the same thing as the other answers suggest; print an inline script in your page head defining the variables, but it also runs the variables through WordPress's esc_js() function, to make sure your output is safe in terms of XSS. Also, since you're tying the variable to a script you have registered with WordPress, you can easily move the script to your footer or to a different page, and the localize script will follow it. Just better practice IMHO. – goldenapples May 04 '11 at 20:48
2

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

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

To extend Milo's answer, you can print out the variable in JS form using PHP's json_encode function.

For instance, if you have an array in PHP

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

That 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. Not all PHP values are json_encodable, of course - objects with methods can't be expressed as javascript values, but it doesn't sound like you're concerned about that.

Cole
  • 1,483
  • 1
  • 11
  • 20