How to generate Javascript within PHP dynamically



Javascripts are executed at the client site, but how do we load certain information that needs to come from the server. Examples would be URLs, language specific messages, etc. What is the best way to get this information from the server to the javascript and store all configurations at one place?

PHP file (vars.php):


<?php
header
("content-type: application/x-javascript");
?>
var foo = '<?php echo $foo?>';
var bar = '<?php echo $bar?>';
?>

HTML file then makes use of above vars.php

<?php
<script type="text/javascript" src="vars.php"></script>
<script type="text/javascript" src="actual_javascript_stuff.js"></script>
?>

This way you can keep all your config in one place. You can include the PHP's config file and populate the JavaScript variables using that.