Forum Moderators: phranque
I'm trying to include php scripts in my .js files, unfortunately I have hit a bit of a snag. It doesn't work. The php code in my .js file is being printed out rather than being parsed.
I've added
AddType application/x-httpd-php .js <?php
header('Content-type: text/javascript');
?> Can anyone shed any light on what has gone wrong? I know all the dodgy work-arounds I can do to get php in there but I just want it to work how it should :)
Welcome to WebmasterWorld!
The basic problem is that JS is client-side, and php is server-side code. So, the JS code is not interpreted, and produces no output (your php code) until after the page has been loaded into the client browser. Since the php interpreter is on the server, it's too late for it to process the code, which exists only in the client browser.
So, bottom line, you can't use JS to output php code and expect it to work unless the client is also running a php interpreter, and is set up to pass the code to it (not a standard browser function).
Jim
StupidScript said: (msg #8 in this thread [webmasterworld.com])
I'm sorry I can't find the thread, but we discussed parsing .JS pages through the PHP engine to keep them from being cached ... with apparent success.i.e.
Add the .JS extension to your httpd.conf or .htaccess file:
AddType application/x-httpd-php .js
In EVERY .JS file, add the appropriate header info with PHP as the FIRST line:
<?php
header("Content-type: text/javascript");
?>
... rest of scripts here ...
Simply add:
# Apply no-cache header to .js files
<FilesMatch "\.js$">
ExpiresDefault A1
Header set Cache-Control: "no-cache, must-revalidate"
</FilesMatch>
Jim