Home > Database > Mysql Tutorial > How to Create Dynamic Dependent Dropdowns Using jQuery, AJAX, PHP, and MySQL?

How to Create Dynamic Dependent Dropdowns Using jQuery, AJAX, PHP, and MySQL?

Barbara Streisand
Release: 2024-11-17 16:54:02
Original
274 people have browsed it

How to Create Dynamic Dependent Dropdowns Using jQuery, AJAX, PHP, and MySQL?

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>');
            }
        });
    });
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template