Home > Database > Mysql Tutorial > How to Dynamically Populate a Dependent Dropdown List Using jQuery, AJAX, PHP, and MySQL?

How to Dynamically Populate a Dependent Dropdown List Using jQuery, AJAX, PHP, and MySQL?

DDD
Release: 2024-11-16 18:10:04
Original
1024 people have browsed it

How to Dynamically Populate a Dependent Dropdown List Using jQuery, AJAX, PHP, and MySQL?

Dynamic Dropdown List Population Using jQuery/AJAX and PHP/MySQL

In this example, we aim to create a set of two dropdown lists, where the second dropdown's options are dynamically populated based on the selection in the first dropdown.

jQuery/AJAX Script:

$(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 in the second dropdown
        $('select#item_2').empty();
        $('select#item_2').append('<option value="0">Select Option</option>');

        // Populate the second dropdown
        $.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

PHP Script:

<?php
require_once('../includes/connect.php');

$item_1_id = $_GET['item_1_id'];

$dbh = get_org_dbh($org_id);

$return_arr = array();

$sth = $dbh->query("SELECT id, name, level 
                     FROM groups
                     WHERE level = '2'
                     AND parent = $item_1_id
                     GROUP by name
                     ORDER BY name");

while ($row = $sth->fetch()) {
  $row_array = array("name" => $row['name'], "id" => $row['id']);
  array_push($return_arr, $row_array);
}

echo json_encode($return_arr);
?>
Copy after login

HTML Markup:

<label>
Copy after login

The above is the detailed content of How to Dynamically Populate a Dependent Dropdown List 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template