Extend two dependent dropdowns by loading the selected record's details after the second list changes.
$( "#subcategory" ).on(
"change",
function () {
const id = $( this ).val();
if ( !id ) {
$( "#detail" ).empty();
return;
}
$( "#detail" ).load(
"record-detail.php",
{ id: id }
);
}
);
$id = filter_input(
INPUT_POST,
'id',
FILTER_VALIDATE_INT
);
$stmt = $connection->prepare(
'SELECT id, name, detail
FROM subcategory
WHERE id = ?'
);
$stmt->bind_param('i', $id);
$stmt->execute();
Demo: linked dropdowns with record details →
See MySQLi SELECT, MySQLi and JSON formatting.
<form method=post action=dd-submit.php>
<select name=category id=category>
<option value='' selected>Select</option>
<?Php
require "config.php";// connection to database
// Query to collect data
$sql="select * from dd2_category where cat_id not in (5,6)";
if ($result_set = $connection->query($sql)) {
while($row = $result_set->fetch_array(MYSQLI_ASSOC)){
echo "<option value=$row[cat_id]>$row[category]</option>";
}
}
echo "</select>";
?>$('#category').change(function(){var cat_id=$('#category').val();$('#sub-category').empty();$.get('ddck.php',{'cat_id':cat_id},function(return_data){$.each(return_data.data, function(key,value){
$("#sub-category").append("
<option value=" + value.subcat_id +">"+value.subcategory+"</option>
");
});
}, "json");<?Php
@$cat_id=$_GET['cat_id'];
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
}
/// end of checking injection attack ////
require "config.php";
$my_array=array();
$sql="select subcategory,subcat_id from dd2_subcategory where cat_id=?";
$result_set = $connection->prepare($sql);
$result_set->bind_param('i',$cat_id);
$result_set->execute();
$result = $result_set->get_result();
while ($row = $result->fetch_assoc()) {
$my_array[]=array("subcat_id"=>$row['subcat_id'],"subcategory"=>$row['subcategory']);
}
$main = array('data'=>$my_array);
echo json_encode($main);
?>$('#sub-category').change(function(){
my_function();
});
///////
my_function=function my_function(){
var subcat_id=$('#sub-category').val();
$.get('dropdown-list-double-dtlck.php',{'subcat_id':subcat_id},function(return_data){
$('#d2').html(return_data); // Record details as returned from database table.
})
}<?Php
$category=$_POST['category'];
$sub_category=$_POST['sub-category'];
echo "Category : $category <br>
Sub-category = $sub_category ";
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.