Parsing php in external javascript (.js) files?

In my external javascript files I often need the value of php variables to be echoed out. For example, I use PHP to dynamically determine the URL to my root directory depending on wether the script is running on my website or localhost. In my javascript, I use the value of this variable so I can, for example, redirect users to the homepage through javascript.

In my .js file if I do something like:


var theurl="<?php echo MY_HOMEPAGE_URL;?>";

then it doesn’t work. My guess is that any php in the .js file doesn’t get parsed. I know that I can add .js files to my apache httpd.conf file so it gets parsed, but I need it to work so that all included files, functions and variables are available to it. (If I use the httpd.conf file method, then the .js file would be considered a standalone php script).

Right now I use desperate measures like, having an <input type=hidden id=“myfield”> field in my html file which contains the value of any variables I need, and in the javascript I use document.getElementById(‘myfield’).value to get the value but I would really like to use a better method. Any ideas?

Just serve up the JavaScript like this:

<script type=“text/javascript” src=“/script.php”></script>

That way the browser knows javascript is coming but the server parses a PHP to generate that javascript.

I know what you’re saying stymee but like I said, then it treats the script.php file as a standalone file, and I want it to be treated like an included file, so all files I have included before and all variables/constants i have defined would still be available in the script.php/script.js file.

you have many options.
you could store you variables in another script, and you script could include this file to get the values it needs. you could also store the values in a database, or even a session.

but…
if your javascript is dynamic, i dont see any good reason to keep it in an external file. you could just put the javascript into the page instead of linking to it as an external file.

you could also pass the variables in the query string, so they would be available to your script.
<script type=“text/javascript” src=“/script.php?myhomepage=foo&anothervar=bar”></script>

passing the variables in the url would allow you to tell the browser to cache the result if your script sent the correct http headers, and it would only grab a fresh copy when the query string changes. caching is one of the benefits of external javascript files. if you dont plan to implement the caching, just put the javascript in the page and do away with the external file. it wont make any difference in that case.