1

I am new to Ajax and PHP and am encountering problems with a dynamic drop down of states and cities. Although I have checked whole lot of answers in stackOverflow but I am not able to get a clear picture as to how we should successfully code to get the desired results.

Problem: Not able to get drop down values for cities, countries and states are successfully getting populated though.

country_back.php [Dynamically generates a drop down for states using country_id]

<?php 

 $con_id=$_POST['id'];


 $con=mysqli_connect("localhost","root","","countries");
 $data=mysqli_query($con,"select * from states where country_id='$con_id' ");
 echo "<select id='st'>";
 while($row=mysqli_fetch_array($data))
   {
     echo "<option value=".$row['id'].">".$row['name']."</option>"; 
   }
 echo "</select>";



?>

ajax file

$("#st").change(function(){
        var s=$(this).val();
        alert(s);   //no value being shown with alert.
        $.ajax=({
            url:"state_back.php",
            method:"post",
            data:{stid:s},
            dataType:"html",
            success:function(strMsg){
                $("#city").html(strMsg);

                }

            })

        })

HTML Form

<form method="post">

<div id="city">
<select>
<option>Cities</option>
</select>
</div>
</form>

state_back.php Dynamically generates a drop down for cities using state_id

<?php

$stid=$_POST['stid'];

$con=mysqli_connect("localhost","root","","countries");
$data=mysqli_query($con,"select * from cities where state_id='$stid' ");
echo "<select>";
while($row=mysqli_fetch_array($data))
{
    echo "<option>".$row['name']."</option>";
}
echo "</select>";


?>
Don'tDownvoteMe
  • 493
  • 2
  • 14

2 Answers2

1

Change your ajax code :

   $(document).on('change', '#st', function(e){
        var s=$('#st').val();
        alert(s);   //no value being shown with alert.
        $.ajax({
            url:"state_back.php",
            method:"post",
            data:{stid:s},
            dataType:"html",
            success:function(strMsg){
                alert(strMsg);
                $("#city").html(strMsg);
                }
            });
        });
Nikita Agrawal
  • 237
  • 1
  • 11
0

Instead of var s=$(this).val(); line try

var s=$('#st option:selected').val();

alert(s);

Anil Kumar Sahu
  • 527
  • 7
  • 26