Home > Backend Development > PHP Tutorial > How to Create a Dependent Dropdown Menu Using PHP and AJAX?

How to Create a Dependent Dropdown Menu Using PHP and AJAX?

Linda Hamilton
Release: 2024-12-15 13:29:14
Original
226 people have browsed it

How to Create a Dependent Dropdown Menu Using PHP and AJAX?

Dynamic Populated Drop Down Box

Problem

You want to create a dynamic drop-down box where the options in the second drop-down box are dependent on the selection made in the first drop-down box.

Database Structure:

Table: category
| id | master | name |
| --- | ------ | ----- |
| 1   | 0 | Main 1 |
| 2   | 1 | Sub 1 |
| 3   | 1 | Sub 2 |
| 4   | 0 | Main 2 |
| 5   | 4 | Sub 3 |
| 6   | 4 | Sub 4 |
Copy after login

PHP Script for Index Page (tester.php):

<select name="master">
Copy after login

PHP Script for Data Population (another_php_file.php):

<?php
if (isset($_POST['master_id']) && $_POST['master_id'] != '') {
    $master_id = $_POST['master_id'];
    $sql = "SELECT * FROM `category` WHERE `master` = ?";
    $statement = $objDb->prepare($sql);
    $statement->execute(array($master_id));
    $list = $statement->fetchAll(PDO::FETCH_ASSOC);
    echo '<option value="" selected disabled>Select Sub</option>';
    if (!empty($list)) {
        foreach ($list as $row) {
            echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
        }
    }
}
?>
Copy after login

The above is the detailed content of How to Create a Dependent Dropdown Menu Using PHP and AJAX?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template