N.K.
N.K.

Reputation: 415

HTML Form. Populate second select from MYSQL Database, based on first select value

I have an HTML Form with 2 select inputs (race_type and race). The first select input is being populated from a mysql database table. The second select input of the form should be populated from the database based on the value of the first select input. I want every time i change the first selection the second selection to be automatically populated again based the new value. How can i achieve that?

 <form action="hidden/add_training.php">

                    <select name="race_type" id="race_type" style="width:300px;" >
                        <option value="">Επέλεξε είδος:</option>
                            <?php 

                                while ($category = mysqli_fetch_array($select_all_race_types,MYSQLI_ASSOC)):; 
                            ?>
                                <option value="<?php echo $category["Race_TypeID"]; 
                                ?>" 
                                
                                <?php if(isset($_SESSION["u_kentroID"])) {if($_SESSION["u_kentroID"]==$category["kentroID"]) {echo ' selected';}    } ?>>
                                    <?php echo $category["name"];
                                    ?>
                                </option>
                            <?php 
                                endwhile; 
                            ?>
                    </select>
                    </br></br>


                    <select name="race" id="race" style="width:300px;">

                        <option value="0">Επέλεξε αγώνισμα:</option>
                            <?php 

                                while ($category = mysqli_fetch_array($select_all_races,MYSQLI_ASSOC)):; 
                            ?>
                                <option value="<?php echo $category["RaceID"]; 
                                ?>" <?php if(isset($_SESSION["u_kentroID"])) {if($_SESSION["u_kentroID"]==$category["kentroID"]) {echo ' selected';}    } ?>>
                                    <?php echo $category["name"];
                                    ?>
                                </option>
                            <?php 
                                endwhile; 
                            ?>
                    </select>
                    </br></br>

                    <input type="submit">
                </form>

I want the second select input to be populated from Mysql database based on the value of the first select input

Upvotes: 1

Views: 678

Answers (1)

Hishan_98
Hishan_98

Reputation: 212

You need to use AJAX POST Request to achieve this particular task. I'll post a similar answer below. I hope it'll help.

index.php

<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

    <style>

    </style>
</head>

<body>
    <form id="update-form">
        <label for="phoneBrand">Choose a Phone Brand:</label>

        <select name="phoneBrand" id="phoneBrand">
            <option value="">No Data</option>
            <option value="samsung">Samsung</option>
        </select>

        <select name="phoneModel" id="phoneModel">
            <option value="">No Data</option>
        </select>
    </form>

    <script>
        //This function will execute on change of selection box One
        $('#phoneBrand').on('change', function() {
            let brand = $("#phoneBrand").val(); //get pre-set value from selection box One
            $.ajax({
                type: "POST",
                url: "phpFile.php",
                data: {
                    brand: brand, // set selection box One value in AJAX POST Request
                    loadModel: true,
                },
                dataType: "JSON",
                beforeSend: function() {
                    //You can Add some functions to do before sending AJAX Request Eg: Page Loader
                },
                success: function(feedback) {
                    if (feedback.status == 1) { //execute if status value 1 on Feed back data from database response

                        const dataArr = feedback.data.split(","); // converting Feedback data value to array
                        for (let index = 0; index < dataArr.length; index++) {
                            addOption("phoneModel", dataArr[index]); // Add new values to selection box Two
                        }

                    } else {
                        console.log("error");
                    }
                },
                error: function(error) {
                    console.log(error);
                },
            });
        });

        //set values in selection box two
        function addOption(parentID, optionValue) {
            $('#' + parentID).append(
                `<option value="${optionValue}">
                    ${optionValue}
                </option>`
            );
        }
    </script>
</body>

</html>

phpFile.php

<?php
//Database Connections
$host = "localhost";
$user = "root";
$password = "";
$db = "test";

$con = mysqli_connect($host, $user, $password, $db);

// Check connection
if ($con->connect_error) {
    echo json_encode(['status' => '0', 'msg' => 'Database Connection error']);
}


if (isset($_POST['loadModel']) && $_POST['loadModel'] == true) {
    try {
        $data = "";
        $brand = $_POST['brand']; //get Brand value from AJAX Request
        $loadSql = "SELECT * FROM phones WHERE brand='" . $brand . "'";
        $loadResult = $con->query($loadSql);
        if ($loadResult->num_rows > 0) {
            // output data of each row
            while ($loadDataRow = $loadResult->fetch_assoc()) {
                $modelName = $loadDataRow["modal"];
                if ($data != "") {
                    $data = $data . ',' . $modelName; // setting values to one string Eg: $data = M1,M11
                } else {
                    $data = $modelName; // setting values to one string Eg: $data = M1,M11
                }
            }

            echo json_encode(['status' => '1', 'msg' => 'Data Found.', 'data' => $data]); //AJAX Success Response
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Cannot Find Selected brand.']); //AJAX Error Response
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => '0', 'msg' => 'Invalid information or Empty data.']);
}
?>

Database

enter image description here

Upvotes: 2

Related Questions