...

View Full Version : Using PHP in external JS file



me'
04-18-2004, 05: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)

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

Scrowler
04-19-2004, 03:38 AM
maybe

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

sad69
04-19-2004, 10: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.

Sadiq.

stophon4
04-19-2004, 10: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>")

mordred
04-19-2004, 11: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
</Files>


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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum