0

I usually include javascript like this:

<script type="text/javascript" src="js/somejs.js">

is there a way like this :

<script type="text/javascript" src="js/somephp.php?js=somejs">

So that the PHP Script echoes a custom generated string or file of requested name

If this is possible how should be the basic php syntax?

Thanks in advance.

Charles
  • 50,943
  • 13
  • 104
  • 142
  • 1
    StackOverflow is not the proper place for this question. We do not write your code for you. You need to do your own coding and if you aren't sure why something is not working as expected, post the code with an explanation of what you were expecting it to do, and what it is actually doing including all error messages. See [ask advice](http://stackoverflow.com/questions/ask-advice). – John Conde Jan 30 '13 at 00:35
  • possible duplicate of [Generate Javascript file with PHP](http://stackoverflow.com/questions/13230411/generate-javascript-file-with-php) – bfavaretto Jan 30 '13 at 00:39
  • @JonathanKuhn : I dint try because i didn't know how to return such a file from server – Sirajul Muneer Feb 14 '13 at 14:46
  • @JohnConde :Sorry. Next time i'd follow the way you suggested. Thanks for the advice. – Sirajul Muneer Feb 14 '13 at 14:50

2 Answers2

3

Yes, it's possible. The script tag doesn't care whether the URL it's pointed at ends with '.js' or not. If you point it at some URL that will serve valid javascript, then you're all good, whether that URL ends in '.js' or '.php' or anything else, and whether the mechanism for serving it is your apache server serving a file straight from the file system, a PHP file echoing out the javascript, or anything else that you please.

If you do decide to serve JavaScript by echoing it out via PHP, to be neat and correct you should set the content type header to 'application/javascript' by calling header('Content-type: application/javascript'); respectively.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
2

As @Mark Amery said it can be done just as you shown, but you should probably include

header('Content-Type: application/javascript');

It will most probably work in all browsers even without it but browsers will complain about it silently.

Chrome throws this for example in the console if you don't include header part:

Resource interpreted as script but transferred with MIME type text/plain