How can PHP be used to dynamically update the options of a second dropdown menu based on the selection in the first dropdown menu?

To dynamically update the options of a second dropdown menu based on the selection in the first dropdown menu, you can use AJAX in combination with PHP. When the value of the first dropdown menu changes, an AJAX request is sent to a PHP script that fetches the corresponding options for the second dropdown menu and returns them as a response. This response is then used to update the options of the second dropdown menu dynamically without reloading the page.

// HTML code for the first dropdown menu
<select id="firstDropdown">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

// HTML code for the second dropdown menu
<select id="secondDropdown"></select>

// JavaScript code to handle the AJAX request
<script>
  document.getElementById('firstDropdown').addEventListener('change', function() {
    var selectedValue = this.value;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'getOptions.php?selectedValue=' + selectedValue, true);
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        document.getElementById('secondDropdown').innerHTML = xhr.responseText;
      }
    };
    xhr.send();
  });
</script>

// PHP code in getOptions.php to fetch and return options for the second dropdown menu
<?php
$selectedValue = $_GET['selectedValue'];

// Query database or perform any other logic to fetch options based on the selected value
$options = array(
  'Option A',
  'Option B',
  'Option C'
);

foreach ($options as $option) {
  echo "<option value='$option'>$option</option>";
}
?>