How can you dynamically fill a select box based on the value of another select box in PHP?
To dynamically fill a select box based on the value of another select box in PHP, you can use AJAX to fetch the options from the server based on the selected value of the first select box. When the value of the first select box changes, an AJAX request is sent to the server to fetch the corresponding options for the second select box, which are then dynamically populated.
// HTML code for the two select boxes
<select id="select1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select id="select2"></select>
// JavaScript code to handle the change event of select1 and fetch options for select2
<script>
document.getElementById('select1').addEventListener('change', function() {
var selectedValue = this.value;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'get_options.php?selectedValue=' + selectedValue, true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var options = JSON.parse(xhr.responseText);
var select2 = document.getElementById('select2');
select2.innerHTML = '';
options.forEach(function(option) {
var opt = document.createElement('option');
opt.value = option.value;
opt.innerHTML = option.text;
select2.appendChild(opt);
});
}
};
xhr.send();
});
</script>
// PHP code in get_options.php to fetch options based on the selected value of select1
<?php
$selectedValue = $_GET['selectedValue'];
// Fetch options based on selectedValue
$options = [
['value' => '1', 'text' => 'Option A'],
['value' => '2', 'text' => 'Option B'],
];
echo json_encode($options);
?>