I have two dropdowns generating from MySQL database. The second dropdown is based on the first dropdown select option.
The problem is that, I am unable to generate the second dropdown data.
I am getting the second dropdown values as Undefined
. But the number of values that should come in the second dropdown is correct.
Please suggest where am I doing wrong. Thanks.
Below are my codes:
Index.php (connection)
<?php
//Create the connection
$con = mysqli_connect("localhost","root","root","echodeve_mfb_temp") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT bp_id, bp_name FROM mfb_billing";
// Execute the query.
$query = mysqli_query($con, $strSQL);
// Close the connection
//mysqli_close($con);
?>
Index.php (Script)
<script>
$(document).ready(function() {
$("#item_1").change(function () {
var group_id = $(this).val();
$.ajax({
type: "POST",
url: "dropdown_select.php?item_1_id=" + group_id,
dataType: "json",
success: function(data){
//Clear options corresponding to earlier option of first dropdown
$('select#item_2').empty();
$('select#item_2').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data, function(i, val){
$('select#item_2').append('<option value="' + val.hospital_id + '">' + val.hospital_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>');
}
})
});
});
</script>
</head>
Index.php (HTML)
<body>
<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
<option value="">Select</option>
<?php
while($row = mysqli_fetch_array($query)) {
echo '<option value="'.$row['bp_id'].'">'.$row['bp_name'].'</option>'."
";
}
?>
</select>
<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />
</select>
</body>
dropdown_select.php (Processing PHP)
<?php
$item_1_id = $_GET['item_1_id'];
//Create the connection
$con = mysqli_connect("localhost","root","root","echodeve_mfb_temp") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT hospital_id, hospital_name FROM mfb_hospital WHERE bp_id = $item_1_id";
// Execute the query.
$query = mysqli_query($con, $strSQL);
$return_arr = array();
while($row = mysqli_fetch_array($query)) {
$row_array = array("name" => $row['hospital_name'],
"id" => $row['hospital_id']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>