Use .php file instead of .js

3

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 with script 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?

    
asked by anonymous 25.06.2018 / 02:10

1 answer

4

You can do this, but with PHP you need to inform that the HTTP response you will return will be a JS code so that the client (browser) can interpret correctly. In fact, the file extension does not matter, it is just an extension of the file name to assist users and some parts of the operating system so that you do not need to read the file's metadata to get its type. In this case, I believe that web servers are preconfigured to send in the response the header for the file type based on its extension, so just writing the JS code in a file with PHP extension may not work in some cases, so need to correctly inform the header.

This happens through the Content-Type header.

Content-Type: application/javascript

So, you just have to write, for example:

<?php

// script.php

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

echo "console.log('Olá mundo')";

And call the file:

<script src="script.php"></script>

That the message will be displayed in the console, since it will be a valid JavaScript HTTP response - something like:

HTTP/1.1 200 OK
Content-Type: application/javascript
Content-Length: 24

console.log('Olá mundo')

That would be the same response generated by the web server for a static JS file with that same content.

Note: Note that this is not conceptually writing JS with PHP , it's just writing a text that will be interpreted as JS code on the client . For PHP, it makes no difference, it will always be text. Strictly speaking, you will only be generating formatted text that can be parsed as JS.

    
25.06.2018 / 02:17