I am trying to pass a value of a select option input using Ajax into another page PHP and get the database and fetch data into select option. However, my problem is there is nothing to show in second select option.
I have the select option called Country which contains Country 1, Country 2, Country 3, Country 4 with cid 1,2,3,4.
what I wanted is past Country ID (cid) into getdata.php and query the database of City which contains City a, city b, city c, etc. and fetch city's data into select option using Ajax.
I need to make city select option dynamically change when I select the country.
here is my database structure :
Country.db
City.db
Here is my script :
dropdown.php
<?php
require_once "connection.php";
?>
<html>
<head>
<title>Dropdown ajax</title>
</head>
<body>
<div class="country" >
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value=""> -- Select Country -- </option>
<!-- populate value using php -->
<?php
$query = "SELECT * FROM country";
$result = mysqli_query($con,$query);
//loop
foreach ($result as $country) {
?>
<option value="<?php echo $country["cid"]; ?>"> <?php echo $country["country"]; ?> </option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="jquery-3.2.1.min"></script>
<script type="text/javascript">
function getId(val){
// ajax function
$.ajax({
type:"POST",
url:"getdata.php",
data:"cid="+val,
success:function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
from the dropdown, I am trying to past cid into getdata.php using ajax and fetch the database into select option inside drop-down.php
getdata.php
<?php
require_once "connection.php";
if(!empty($_POST["cid"])){
$cid = $_POST["cid"];
$query = "SELECT * FROM city WHERE cid = $cid";
$result = mysqli_query($con,$query);
foreach ($result as $city) {
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?></option>
<?php
}
}
?>
here is my connection.php
<?php
$con = mysqli_connect("localhost","root","admin","dropdowndb");
//check connection
if(mysqli_connect_errno()){
echo "Failed to connect :".mysqli_connect_errno();
}
?>
the result is like this :
so how to fix this problem?