Dynamic Cascading Dropdown Boxes
This example demonstrates the creation of a dynamic drop-down box that populates the second drop-down box based on the selection of the first drop-down box, as required.
Explanation:
First Drop-Down Box:
jQuery/AJAX:
update.php:
AJAX Success Function:
Example Code:
tester.php:
<select name="gender">
update.php:
if (!empty($_GET['id']) && !empty($_GET['value'])) { $id = $_GET['id']; $value = $_GET['value']; $sql = "SELECT * FROM `category` WHERE `master` = ?"; $statement = $objDb->prepare($sql); $statement->execute(array($value)); $list = $statement->fetchAll(PDO::FETCH_ASSOC); if (!empty($list)) { $out = array('<option value="">Select one</option>'); foreach ($list as $row) { $out[] = '<option value="' . $row['id'] . '">' . $row['name'] . '</option>'; } echo json_encode(array('error' => false, 'list' => implode('', $out))); } else { echo json_encode(array('error' => true)); } } else { echo json_encode(array('error' => true)); }
Mechanism:
By following these steps, you can create cascading drop-down boxes that provide a user-friendly and responsive interface for data selection.
The above is the detailed content of How to Create Dynamic Cascading Dropdown Boxes using jQuery and AJAX?. For more information, please follow other related articles on the PHP Chinese website!