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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

nice, didn't know about that one.
@goldenapples, Thanks. Can you say why is this way better?
@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.
2

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

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

Comments

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.

Comments