Display dynamic dropdown list – PHP

In this tutorial, we will be creating a dynamic dropdown to display list of orders. On selecting order from list, we display all product’s code in that order. And on selecting the product code, it will display the product’s detail.

We will be using a sample database named classicmodels, it is attached in the source files below. You can also download it from here.

Populate first dropdown

Create a file named index.php and create an empty <select> tag with a unique ID. We will be populating orders list in this dropdown.

<p>Orders</p>
<select id="orders">
    
</select>

Now create a function to populate all orders in this dropdown and call that function as soon as the page loads. We will be using pure Javascript in this tutorial, no jQuery is required.

<script type="text/javascript">
    function getOrders() {
        // Creating an AJAX object
        var ajax = new XMLHttpRequest();

        // A separate file is created to get orders list
        ajax.open("GET", "get-orders.php", true);

        // Actually sending the request to get data
        ajax.send();

        // Callback when request status changes
        ajax.onreadystatechange = function () {

            // readyState = 4, when the response is received
            // status = 200, when the request is successfull
            if (this.readyState == 4 && this.status == 200) {

                // this.responseText will be JSON string, so we are converting it in Javascript object
                // using function JSON.parse 
                var response = JSON.parse(this.responseText);

                // html variable will contain all list items as String
                var html = "<option>Select order</option>";

                for (var a = 0; a < response.length; a++) {
                    // Value attribute will be used to get order details
                    html += "<option value='" + response[a].orderNumber + "'>";

                        // This will be displayed to users
                        html += response[a].orderNumber;
                    html += "</option>";
                }

                // Adding items in <select> tag
                document.getElementById("orders").innerHTML = html;
            }
        };
    }

    // Calling the above created function when page loads.
    getOrders();
</script>

Now go ahead and create a file named get-orders.php and in this file, simply get all the orders from database table orders and return as JSON.

<?php

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM orders";
$result = mysqli_query($connection, $sql);

$data = array();

while ($row = mysqli_fetch_object($result))
    array_push($data, $row);

echo json_encode($data);

At this point, you will be able to see a list of orders in your first dropdown. The next step is to get all product’s code when user select any order from this list.

Populate second dropdown based on first value

First, attach an event that will be called when the user select any item from order’s list. Notice it is sending this.value which means user selected order number:

<p>Orders</p>
<select id="orders" onchange="getDetail(this.value);">
    
</select>

Now create a function to get all product’s code that have the same orderNumber as user has selected. Notice that we are sending orderNumber as parameter so we can get the record of only that order number:

function getDetail(orderNumber) {
    var ajax = new XMLHttpRequest();
    ajax.open("GET", "get-order-detail.php?orderNumber=" + orderNumber, true);
    ajax.send();

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var response = JSON.parse(this.responseText);
            var html = "<option>Select product code</option>";
            for (var a = 0; a < response.length; a++) {
                html += "<option value='" + response[a].productCode + "'>";
                    html += response[a].productCode;
                html += "</option>";
            }
            document.getElementById("order-details").innerHTML = html;
        }
    };
}

Now, go ahead and create a file named get-order-detail.php and in this file, we will be getting records of only user selected order.

<?php

$orderNumber = $_GET["orderNumber"];
$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM orderdetails WHERE orderNumber='$orderNumber'";
$result = mysqli_query($connection, $sql);

$data = array();

while ($row = mysqli_fetch_object($result))
    array_push($data, $row);

echo json_encode($data);

Now you will be able to see the values in 2nd dropdown as soon as you select some value from first dropdown. So we can say that our 2nd dropdown list is now dynamic. Because its value changes with respective to the 1st dropdown.

Browse our more free PHP tutorials.

[wpdm_package id=’127′]

Leave a Reply

Your email address will not be published. Required fields are marked *