How can PHP developers effectively retrieve and use the ID of a selected item in a dropdown menu populated from a database?

When a dropdown menu is populated from a database, each item typically has an associated ID. To effectively retrieve and use the ID of a selected item, you can utilize JavaScript to capture the selected option's value and send it to a PHP script for further processing. This can be achieved by adding an onchange event listener to the dropdown menu and using AJAX to send the selected ID to the server-side PHP script.

// HTML code for the dropdown menu
<select id="dropdown" onchange="getSelectedId()">
    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
</select>

// JavaScript function to get the selected ID and send it to a PHP script
<script>
function getSelectedId() {
    var selectedId = document.getElementById("dropdown").value;
    
    // Send the selected ID to a PHP script using AJAX
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'process.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send('selectedId=' + selectedId);
}
</script>

// PHP script (process.php) to retrieve the selected ID and perform further actions
<?php
if(isset($_POST['selectedId'])) {
    $selectedId = $_POST['selectedId'];
    
    // Perform further actions with the selected ID
    echo "Selected ID: " . $selectedId;
}
?>