I have a PHP code that retrieve data from MYSQL database and includes these retrieved data into a dropdown list where 2 dropdown list exist, the user select from the first one and based on his selection the second one will display the related data.
- tbl_country:
- country_id
- country_name
- tbl_state:
- state_id
- state_name
- country_id
can anyone tell me where the error in the code?
code 1:
<?php
function load_country(){
$connect = mysqli_connect("localhost","****","***","test");
$output = '';
$sql = "select * from tbl_country";
$result = mysqli_query($connect,$sql);
// var_dump($result);
while ($row = mysqli_fetch_array($result)) {
$output.='<option value="'.$row["country_id"].'">'.$row["country_name"].'</option>';
}
return $output;
}
?>
<html>
<head>
<title>dropdown test</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').change(function(){
var country_id = $(this).val();
$.ajax({
url:"dropdown_fetch.php",
method:"POST",
data:{countryId:country_id},
datatype:"text",
success:function(data){
$('#state').html(data);
}
});
});
});
</script>
</head>
<body>
<p>select owner
<select name="country" id="country">
<option value="">Select country</option>
<?php echo load_country(); ?>
</select></p>
<p>select state
<select name="state" id="state">
<option value="">Select state</option>
</select></p>
</body>
</html>
code 2:
<?php
$connect= mysqli_connect("localhost","****","****","test");
$output = '';
$sql = "select * from state where country_id = '".$_POST["countryId"]."' ORDER BY country_name";
$result = mysqli_query($connect,$sql);
//var_dump($_POST["ownerID"]);
$output='<option value="">Select state</option>';
while ($row = mysqli_fetch_array($result) {
$output.='<option value="'.$row["state_id"].'">'.$row["state_name"].'</option>';
}
echo $output;
?>