Home >Backend Development >PHP Tutorial >How to Populate a Dependent Dropdown Box Using AJAX and PHP?
How can I populate a dynamic drop down box based on the selection of another drop down box?
I have a database table called category as shown below:
[Image of a database table named "category" with columns "id", "name", and "master"]
I am trying to do a dynamic drop down box and the index script is shown as:
[Code sample of the index script]
The update.php is shown as:
[Code sample of the update.php]
The 2nd drop down box is not showing the values dependent on the 1st drop down box as shown:
[Image of a form with two drop down boxes. The first drop down box has options for "Select one", "Category 1", and "Category 2". The second drop down box has only the option "----".]
Can someone help me please.
Answer:
To create a dynamic drop down box where the options in the second box depend on the selection in the first box, you can use the following approach:
Here is an example that demonstrates this approach:
tester.php:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function() { $('#first_dropdown').change(function() { var value = $(this).val(); $.ajax({ url: 'update.php', method: 'POST', data: { value: value }, success: function(response) { $('#second_dropdown').html(response); $('#second_dropdown').prop('disabled', false); } }); }); }); </script> </head> <body> <select>
update.php:
<?php if (isset($_POST['value'])) { $selectedValue = $_POST['value']; $data = array(); // Here you would typically query your database to retrieve options based on the selected value. if ($selectedValue == 'category1') { $data[] = '<option value="option1">Option 1</option>'; $data[] = '<option value="option2">Option 2</option>'; } elseif ($selectedValue == 'category2') { $data[] = '<option value="option3">Option 3</option>'; $data[] = '<option value="option4">Option 4</option>'; } echo implode('', $data); } ?>
By following this approach, you can create multi-level dynamic drop down boxes where the options in each drop down box are dependent on the selection made in the previous drop down box.
The above is the detailed content of How to Populate a Dependent Dropdown Box Using AJAX and PHP?. For more information, please follow other related articles on the PHP Chinese website!