View Full Version : Using PHP in external JS file

04-18-2004, 04:55 PM
I have a JS file linked with <script src="...">, which I want to use PHP variables in. Is there any way of doing this? I tried a simple test:
<?php echo "alert('hello world!')" ?>Which gave me a syntax error (the php code was not executed).

Is there something like eval(); that I can use? (Note: I want the file to remain external, it's not the shortest of files)

04-19-2004, 01:54 AM
trying renaming your javascript file from script.js to script.php

04-19-2004, 02:38 AM

echo "<script>alert('hello world');</script>";

04-19-2004, 09:29 PM
I think dswimboy is right. If you don't want to rename your file, you'll have to add the .js extension to your server to be parsed as a PHP file.


04-19-2004, 09:52 PM
No, I tested it all you got to do is:

echo ("<script src = 'wahteveritis.js'></script>")

Or the tested thing:

echo ("<script>alert('Hello World')</script>")

04-19-2004, 10:28 PM
stophon, I think you misunderstood me's question: He wants to use PHP in his external JavaScript file, not in the file where the script gets included. And to reiterate: Both dswimboy and sad69 are right, the server needs to hand over the javascript file to the PHP interpreter before sending it to the client. The easiest way is by renaming the file, another possiblity would be to use a .htaccess file with

<Files external.js>
ForceType application/x-httpd-php

in it. Presumes that you're running this on Apache, and have permissions to use .htaccess files. And of course external.js must be the name of the JS file in question.