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?
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:
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!