A JS function needs a variable, generated by PHP. The .js files can't interpret <?php ?>
strings, so I must pass it from the .html code.
Yes, but running JS code from HTML considered bad practice (just like style
elements). Then what to do?
A JS function needs a variable, generated by PHP. The .js files can't interpret <?php ?>
strings, so I must pass it from the .html code.
Yes, but running JS code from HTML considered bad practice (just like style
elements). Then what to do?
You could use echo to do something like this:
<? echo('<script type="text/javascript">var hello="world"</script>');
There are a couple of options. Firstly you can build off your first example.
<?php
$myVariable = array('key' => 'value', 'anotherKey' => 10);
?>
// PHP variable output in javascript's object syntax
var phpData = <?php echo json_encode($myVariable); ?>;
// value
console.log(phpData.key);
// 10
console.log(phpData.anotherKey);
Another option would be to use Ajax requests to the PHP script to retrieve data. Based on your question, this option most likely won't be useful because you have the data when the page loads.
The .js files can't interpret
<?php ?>
strings
So give the file a .php
extension. (Make sure you override PHP's default Content-Type output with a header()
call.
but running JS code from HTML considered bad practice (just like style elements).
That's because inlining JS is bad for caching. If the file is being dynamically generated, then you may not be able to sanely cache it anyway.