Home >Backend Development >PHP Tutorial >How can I dynamically populate a second drop-down box based on the selection in a first drop-down box using jQuery and PHP?

How can I dynamically populate a second drop-down box based on the selection in a first drop-down box using jQuery and PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 08:18:16871browse

How can I dynamically populate a second drop-down box based on the selection in a first drop-down box using jQuery and PHP?

Dynamically Populating Drop-Down Boxes

A popular technique used in web development is to create interactive web forms where drop-down boxes can display options that depend on the selected value of a preceding drop-down box. This functionality is commonly achieved using a combination of JavaScript (jQuery) and server-side scripting (PHP).

Example Code Explanation

In this specific scenario, you are trying to populate the second drop-down box based on the value selected in the first drop-down box. The code provided accomplishes this by using the following steps:

  1. Capturing the User's Selection: When the user changes the selection in the first drop-down box, a jQuery event handler is triggered. This handler captures the value of the selected option using $(this).val().
  2. Sending a Request: Using jQuery's AJAX capabilities, an asynchronous request is sent to the server-side PHP script, another_php_file.php. Along with the request, the value of the selected option sel_stud is passed as data.
  3. Server-Side Processing: The another_php_file.php script receives the posted data, performs the necessary database queries to retrieve relevant data specific to the selected option, and assembles a response containing HTML markup for the updated second drop-down box.
  4. Updating the Drop-Down Box: The response received from the server is processed by the AJAX success handler function. The HTML markup for the second drop-down box is injected into the DOM using $('#LaDIV').html(whatigot);.

Customized Example

This code example demonstrates a customized implementation where the first drop-down box is used to select student names. Upon selection, the second drop-down box displays the corresponding classes taught by that student.

tester.php

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $('#stSelect').change(function() {
                var sel_stud = $(this).val();
                $.ajax({
                    type: "POST",
                    url: "another_php_file.php",
                    data: 'theOption=' + sel_stud,
                    success: function(whatigot) {
                        $('#LaDIV').html(whatigot);
                    }
                });
            });
        });
    </script>
</head>
<body>

    <select name="students">

another_php_file.php

<?php

    // Database Connection
    $server = 'localhost';
    $login = 'root';
    $pword = '';
    $dbname = 'test';
    mysql_connect($server,$login,$pword) or die($connect_error);
    mysql_select_db($dbname) or die($connect_error);

    // Get POST Data
    $selStudent = $_POST['theOption'];

    // Query Database
    $query = "SELECT * FROM `class` WHERE `teacher_id` = $selStudent";
    $result = mysql_query($query) or die('Fn Error: ' . mysql_error());
    $num_rows_returned = mysql_num_rows($result);

    // Build Response HTML
    $r = '
        <select>
    ';

    if ($num_rows_returned > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $r = $r . '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
        }
    } else {
        $r = '<p>No classes taught by this student</p>';
    }

    // Echo Response
    echo $r;
?>

This customized solution tailors the second drop-down box to display classes based on the selected student, providing a flexible and user-friendly form experience for dynamically populated drop-down boxes.

The above is the detailed content of How can I dynamically populate a second drop-down box based on the selection in a first drop-down box using jQuery and PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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