Don'tDownvoteMe
Don'tDownvoteMe

Reputation: 501

Country State Drop Down

I am new to Ajax and PHP and am encountering problems with a dynamic drop down of country and states. 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.

country.php

<form method="post">

<select id="cont">
<option>Select</option>
<?php
$con=mysqli_connect("localhost","root","","countries");
$data=mysqli_query($con,"select * from countries");
while($row=mysqli_fetch_array($data))
{
    echo "<option class='con' value=".$row['id'] .">".$row['name']."</option>"; 
}
?>
</select>

<div id="states">
<select>
<option>Select</option>
</select>
</div>

</form>

ajax file

$(document).ready(function(){

    $("#cont").change(function(){
        var c=$(this).val();
        $.ajax({
            url:"country_back.php",
            method:"post",
            data:{id:c},
            dataType:"html",
            success:function(strMsg){
                ("#states").html(strMsg);
                }

            })

        })

    })

country_back.php[to fetch states data]

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

?>

Upvotes: 1

Views: 1207

Answers (1)

Nikita Agrawal
Nikita Agrawal

Reputation: 235

In your ajax :

$(document).ready(function(){

    $("#cont").change(function(){
        var c=$(this).val();
        $.ajax({
            url:"country_back.php",
            method:"post",
            data:{id:c},
            dataType:"html",
            success:function(strMsg){
                alert(strMsg);
                $("#states").html(strMsg);
                }

            })

        })

    })

PHP CODE :

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

  ?>

Do the changes

Upvotes: 1

Related Questions