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>
share|improve this question
This question should be posted on stackoverflow since it's not Wordpress dependent – Boris Delormas May 4 '11 at 15:26
@Kaaviar - I didn't realize that. Will do next time. – Ash May 4 '11 at 15:40
1  

migrated from wordpress.stackexchange.com May 4 '11 at 19:48

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

share|improve this answer
nice, didn't know about that one. – Milo May 4 '11 at 19:00
@goldenapples, Thanks. Can you say why is this way better? – Ash May 4 '11 at 19:30
The 'Source File' section of this docs page is intriguing. – Cole May 4 '11 at 20:06
@Cole - I know, I was just reading that... its hilarious. – goldenapples May 4 '11 at 20:38
@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 4 '11 at 20:48
show 1 more comment

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

<script type="text/javascript">
var myArray = new Array(<?php echo $myArrayVals; ?>);
</script>
share|improve this answer
@Milo, Thanks. Simple and brilliant. – Ash May 4 '11 at 15:39

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.