I am trying to make a website which will basically have a lot of buttons that will execute a particular PHP file on click and show their results on an empty box on the same screen. These PHP files are present in a directory test_scripts in the same directory as index.php.
I thought that the obvious step would be to create a loop that will iterate over those files and create their ui dynamically. So I wrote the following PHP code in the middle of index.php
#Index.php
...
<?php
$dir_itr = new DirectoryIterator("test_scripts");
foreach ($dir_itr as $file) {
if ($file->isFile()) {
$filename = $file->getFilename();
$formattedFileName =
'<button
class="box button is-large is-fullwidth is-primary is-light"
onclick="loadScriptFileData($filename)">
$filename
</button>';
print $formattedFileName;
}
}
?>
...
The loadScriptFileData() is a JavaScript function written in a script tag present in head:
<!--index.php-->
<script>
function loadScriptFileData(filename) {
alert(filename);
}
</script>
The for each loop is running correctly, but the JavaScript function and the generated HTML is not working correctly. There are the expected number of buttons on the page, but each button just has the name as the word "$filename" and not the actual expected filename. The case is worse with JavaScript, which straight out does not work and gives the error in the console as Uncaught ReferenceError: $filename is not defined at HTMLButtonElement.onclick ((index):71)
Why is the $variable not getting converted to a string? I even tried the toString() function, but still no good. Am I doing it wrong?