I have a database table name country & states I am trying to call states when country is selected every sates has associated country column name XX like for Pakistan PK, for United States of America US and so on my code examples are below to find a solution.
Country Select Box
<select name="country" id="country">
<option value="-1">Select Country</option>
<?php
$query = $mysqli->query("SELECT * FROM `country`");
while ( $row = mysqli_fetch_assoc($query) ) {
echo '<option value="'.$row['country_code'].'">';
echo $row['country_name'];
echo '</option>';
}
?>
State Select Box
<select name="country" id="states">
<option value="-1">Select State</option>
</select>
Ajax Call
$(document).ready(function(){
$('#country').on('change',function(){
var countryCode = $(this).val();
if(countryCode){
$.ajax({
type: "POST",
url: 'getStates.php',
data: {countryCode:country_code},
success:function(data){
$("#states").html(data);
}
});
}
});
});
I have the separate file where I am fetching states with ajax
<?php include_once("inc/config.php");?>
<option value="-1">Select State</option>
<?php
$query = $mysqli->query("SELECT * FROM `state` WHERE `country_code` = '".$_POST['country_code']."' ");
while( $row = mysqli_fetch_array($query) ){
echo '<option value="';
$row['state_id'];
echo '">';
echo $row['state_name'];
echo '</option>';
}
?>
<option value="Other">Other</option>
Note:
Database connection is ok because when I insert 'PK'
instead of '".$_POST['country_code']."'
in getStates.php file it works fine and when I insert console.log()
in ajax success:function(data){console.log()}
it shows related value of country but I think I am doing some mistake somewhere in ajax code.
I also get an undefined variable error when I insert $_POST['country_code']
or $_POST['countryCode']
in getStates.php file.
I am sure there is something wrong in ajax call