I would like to be able to insert html code from javascript, which inserts php code that contains an array. What I do is get in the variable $ teams an array of teams. And then I go through the array with a foreach to set the values in the select options
I have done the following but it does not work.
document.getElementById('selectTeam').innerHTML = '<select class="form-control"><?php $teams = ControllerTeam::ctrTeam(); foreach ($teams as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["name"].'</option>';}?></select>';
First problem is that, probably, the content is loaded after the JS so the selector returns null hence the error in the OP code. Cannot set property 'innerHTML' of null
That means, you should only execute the JS code on window.load
or any other similar event that ensures the fact that the HTML is loaded before trying to execute.
Now, for the other issue in the comments, if you rewrite the PHP code like this :
<?php
$teams = ControllerTeam::ctrTeam();
$options_html = '';
foreach ($teams as $key => $value) {
$options_html .= '<option value="' . $value["id"] . '">' . $value["name"] . '</option>';
}?>
And in the JS - make sure it loads on window.load
or similar -
document.getElementById('selectTeam').innerHTML =
'<select class="form-control"><?php echo $options_html ?></select>';
This makes the code more readable and helps you debug easier.
There is a typo in your code. Please change it to:
document.getElementById('selectTeam').innerHTML = '<select class="form-control"><?php
$teams = ControllerTeam::ctrTeam();
foreach ($teams as $key => $value) {
echo '<option value="' . $value["id"] . '">' . $value["name"] . '</option>';
}
?></select>';