Dynamic Drop Down List in PHP+MySQL using AJAX & jQuery

Spread the love

Project – Dynamic Drop Down List in PHP+MySQL using AJAX & jQuery

Solution

  • Database Name – ajax-menu
  • Total Table – 2
  • Table Name – categories & subcategories
  • categories Table – 2 Field – id(int, auto_increment, primary), name(varchar, 255)
  • subcategories Table – 3 Field – id(int, auto_increment, primary), category_id(int not null), name(varchar, 255)

Index.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Auto Load Submenu - By Hindialerts.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12 d-flex flex-column justify-content-center align-items-center" style="height:100vh">
                <select name="" id="category" class="form-control mb-5"></select>
                <select name="" id="subcategory" class="form-control"></select>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="ajax.js"></script>
</body>

</html>

db.php

<?php

$conn = new mysqli('localhost', 'root', '', 'ajax-menu');

if ($conn->connect_error) {
    die("Connection Failed");
}

response.php

<?php

include 'db.php';

if (isset($_POST['getMenu'])) {
    $query = "SELECT * FROM `categories`";
    $result = $conn->query($query);
    if ($result->num_rows > 0) {
        $opt = "<option>Select Your Category</option>";
        while ($row = $result->fetch_assoc()) {
            $opt .= "<option id='item' value='{$row['id']}'>{$row['name']}</option>";
        }
        echo $opt;
    } else {
        echo "<option>Select Your Category</option>";
    }
}
if (isset($_POST['getSubMenu']) && isset($_POST['id'])) {
    $query = "SELECT * FROM `subcategories` WHERE category_id=" . $_POST['id'];
    $result = $conn->query($query);
    if ($result->num_rows > 0) {
        $opt = "<option>Select Your Sub Category</option>";
        while ($row = $result->fetch_assoc()) {
            echo "<option value='{$row['id']}'>{$row['name']}</option>";
        }
    } else {
        echo "<option>Select Your Sub Category</option>";
    }
}

Now is the magic part – Ajax.js file

$(document).ready(function () {
    $.ajax({
        url: 'response.php',
        method: "POST",
        data: { getMenu: 1 },
        success: function (res) {
            $("#category").html(res)
        }
    })
});
$(document).on("change", "#category", function () {
    let id = $(this).val();
    $.ajax({
        url: 'response.php',
        method: "POST",
        data: { getSubMenu: 1, id: id },
        success: function (res) {
            $("#subcategory").html(res);
        }
    });
});

This is only for learning purpose that you can understand easily. but you can make only one or more php file for making your project as small as possible. If you get any error or want to something new to learn share details below.

Other Important Topics

Be the first to comment

Leave a Reply

Your email address will not be published.


*