Dynamic Dropdowns with jQuery/AJAX and PHP/MySQL
Problem:
Constructing a set of dynamic dropdown boxes using jQuery/AJAX and PHP/MySQL where the second dropdown's options depend on the selection in the first dropdown.
JSON Query:
The provided JSON query for generating the second dropdown's values functions correctly. However, there are issues populating the options into the dropdown form element.
Javascript:
The main error lies within the event handler for the first dropdown. The modified code should resemble:
$().ready(function () { $("#item_1").change(function () { var group_id = $(this).val(); $.ajax({ type: "POST", url: "../../db/groups.php?item_1_id=" + group_id, dataType: "json", success: function (data) { // Clear previous options $('select#item_2').empty(); $('select#item_2').append('<option value="0">Select Option</option>'); // Populate options from JSON $.each(data.subjects, function (i, val) { $('select#item_2').append('<option value="' + val.id + '">' + val.name + '</option>'); }); $('select#item_2').focus(); }, beforeSend: function () { $('select#item_2').empty(); $('select#item_2').append('<option value="0">Loading...</option>'); }, error: function () { $('select#item_2').attr('disabled', true); $('select#item_2').empty(); $('select#item_2').append('<option value="0">No Options</option>'); } }); }); });
HTML:
The HTML code provided appears correct.
PHP:
The PHP code for retrieving the JSON data is also correct.
Sample JSON Output:
The sample JSON output provided is valid and will be parsed correctly by the jQuery code.
The above is the detailed content of How to Create Dynamic Dependent Dropdowns Using jQuery, AJAX, PHP, and MySQL?. For more information, please follow other related articles on the PHP Chinese website!