0

I am trying to get a country, state, city dependent selection boxes to work(once country is picked then state will populate with the related states then state is picked etc...) but I think there is something wrong with my jquery or ajax because my state box won't populate. If you could help find where the code goes wrong I would appreciate it. Also I would like to know how the ajax posts back to the shippingaddress.php page.(is it in the success callback?) Do the select boxes need to be contained in a form or will they post with out it? Thank you in advance for any help!

shippingaddress.php

<div class="select-boxes">
<form action="" method="post">
<?php
//Get all country data

$query = $conn->query("SELECT * FROM countries WHERE status = 1 ORDER BY 
country_name ASC");

//Count total number of rows
$rowCount = $query->num_rows;
?>

<select name="country_id" id="country">
<option value="">Select Country</option>

<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option 
value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>

</select>
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
</form>
</div>

<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

ajaxData.php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "secure_login";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $conn->query("SELECT * FROM states WHERE country_id = 
".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $conn->query("SELECT * FROM cities WHERE state_id = 
".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
  • sorry, there's too much code (in not the best formatting) for such a general quastion like "where the code goes wrong". Please do some debugging first and share the results with us. Also it would be much appreciated to narrow down your code to a minimal example. – Jeff May 21 '18 at 22:24
  • did you check: the ajax request is successfull? Php receives all neccessary values? The db query doesn't throw an error? The return from php is as expected? .... – Jeff May 21 '18 at 22:27
  • As mentioned above, your code is too long for the question. As an basic approach, you could call the php code using Ajax and let it return an array to you and you parse that array with JS instead and populate your drop down menus. Much cleaner than trying to do it all in PHP. All your ajaxData.php should be doing is to send a list of entries back to the shippingaddress.php. – Paulo Hgo May 21 '18 at 22:47
  • I inserted an window.alert(); into the ajax used for the countries selection box and I didn't get an alert. How can I trouble shoot that? – user9555327 May 21 '18 at 22:49
  • Take a look at [this article](https://stackoverflow.com/questions/14918462/get-response-from-php-file-using-ajax) to understand how Ajax retrieves data back. You can also debug PHP using [ChromePhp](https://github.com/ccampbell/chromephp). It can come in pretty handy. – Paulo Hgo May 21 '18 at 23:15
  • @user9555327 - what error you got in console log? – Jaydp May 21 '18 at 23:52
  • Uncaught ReferenceError: $ is not defined at shippingaddress.php:95 – user9555327 May 21 '18 at 23:58
  • I assume that is referencing the $ in my javascript which should stand for Jquery if i'm not mistaken. How can I make sure it is referencing jquery properly? – user9555327 May 22 '18 at 00:10
  • It would seem that $ is not referencing jquery. How can I make it reference jquery properly? – user9555327 May 22 '18 at 00:29
  • Ok so I fixed the reference to jquery by moving my refrence to the top of the page. Now I am getting this error in the console: shipping address.php:113 Uncaught ReferenceError: response is not defined at Object.success (shippingaddress.php:113) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at A (jquery.min.js:4) at XMLHttpRequest. (jquery.min.js:4) – user9555327 May 22 '18 at 00:37
  • Move jquery.min.js include file to the top of your js code. Also using the Web developer tool -> Network, choose ajaxData.php, then check if there's any error(s) from the response tab. You may be getting errors from ajaxData.php that's not visible to you. – Karlo Kokkak May 22 '18 at 01:24

0 Answers0