Reputation:
I would love to post some starting code in this question, but to be honest, I' stumped.
I'm looking for a way to use PHP within my .JS file.
I would like to be able to use real PHP functions inside my "stuff.js" and then be able to include it using:
<script type="text/javascript" src="whatever.js"></script>
Any thoughts? Thanks.
Upvotes: 0
Views: 373
Reputation: 14992
You just have to write your JavaScript into a php file and then include it
<script type="text/javascript" src="whatever.php"></script>
I would recommend you keeping your JS functions in a .js file and the variable data that needs to be output dynamically could be output directly in the main php/html file:
<script type="text/javascript" language="JavaScript">
var a = "<?php echo addslashes($a); ?>";
// ...
</script>
Other possibility would be to tell your server to proccess *.js file with php but I wouldn't recommend that as it could cause some unexpected problems.
Upvotes: 1
Reputation: 3559
<script src="/YOUR_PHP_FILE_PATH/file.php"></script>
Also add header in php file
header(Content-Type: text/javascript);
Upvotes: 1
Reputation: 152206
It's impossible but you can use PHP file as a JavaScript file talking in a short way. ;)
<script type="text/javascript" src="whatever.php"></script>
And in whatever.php
:
<?php
echo "var text = 'test';";
?>
alert(text);
Upvotes: 0