1

i have a question when a .php file called as a javascript what dose this mean? and when this is needed to be used ?

ex:

<head> 
<script src="dir/myphpfile.php" type="text/javascript"></script>
</head> 
4
  • 1
    This is essentially how JSON-P works. Commented Jul 10, 2012 at 6:59
  • @TheZ no particular reson to assume Json being returned. It could just as easily be a way tu return all script in one request or to include server vars in a script. Commented Jul 10, 2012 at 7:03
  • @mplungjan The PHP call to the server will return Javascript (be it static or dynamic) lest it throw an error in the browser. JSON-P is just JSON that has been wrapped up to look like Javascript so that the browser can load it in from any domain. Commented Jul 10, 2012 at 7:05
  • I know this. I would rarely expect JSON in a script tag, just normal scripts. Most JSONP I have seen is invoked using appends to the head Commented Jul 10, 2012 at 7:09

2 Answers 2

7

This means that the myphpfile.php would generate javascript code as output instead of HTML because that's all that the web browser could understand in a script tag. It is useful in situations when you want to generate dnyamic javascript at runtime instead of statically coding it in a separate .js file. Think for example declaring a javascript variable containing the list of customers stored in a database on the server and making this javascript variable globally accessible.

Another common example where this could be useful is to implement JSONP allowing cross domain AJAX requests.

Yet another example is to use a php script that will combine and cache the output of multiple javascript files into one.

Sign up to request clarification or add additional context in comments.

3 Comments

Or if you want to combine multiple JS files via PHP into one file to get less http requests for mobile phones for example.
@Asto, excellent example. I have updated my answer to include it. Thanks for pointing this out.
@aadiahg, do you have further questions? If not you might consider marking an answer by clicking on the tick next to it: meta.stackexchange.com/questions/5234/…
1

as Darin Dimitrov said it can be used to generate dynamic javascript at runtime or sometimes also used for on the fly minifying of javascript files.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.