I want to know if I can include php scripts in javascript[1] the same way it can be done in html[2]
server.php:
<?php
echo 'hello World';
?>
client.js (or client.php if necessary):
function foo() {
var i = <?php include('server.php'); ?>
console.log( i );
}
If it can be done, and if client.php must be used instead, I would really appreciate a minimal example with index.html/index.php as well, since I would like to see how I would include client now that it is a php file and not javascript
You can use output buffering to achieve something similar, although it’s not possible to directly embed PHP code in JS.
Example:
server.php
client.php – (.php extension enables the ability to parse PHP tags, but really outputs JS)
Edit:
If the server.php file will only return a simple string, then you can modify your code for client.php. Notice how I said “return” instead of output – If your server.php outputs anything, it will be sent to the browser as output (not what you want). Alternatively, you can set a variable in server.php which gets outputted in client.php, or encapsulate your code in a function:
server.php
client.php
Note: You may also want to add a call to
html_entitiesorhtmlspecialchars.