I want to use an external .js
(JavaScript) file in my project but would like to use PHP code to handle JavaScript within .js
. I know the .js
extension will treat the file as JavaScript and if I enter <?php ... ?>
will result in an error as this is not part of the JavaScript syntax.
Using the JavaScript code on the same page
.php
withscript
is easy because just merge PHP code with JavaScript to change the code. Ex.:<script> var string = "<?=$variável?>"; </script>
But by simulating an external .js
via PHP, you can call:
<script src="pagina.php"></script>
And treat this pagina.php
page as if it were a .js
file so that I can use PHP codes (connect to database etc.) to do what I want and return only JavaScript codes handled by PHP?