title: Country State Drop Down
body: <p>I am new to Ajax and PHP and am encountering problems with a dynamic drop down of country and states. <b>Although I have checked whole lot of answers in stackOverflow</b> but I am not able to get a clear picture as to how we should successfully code to get the desired results.</p>
  
  <p><code>country.php</code></p>
  
  <pre><code>&lt;form method="post"&gt;
  
  &lt;select id="cont"&gt;
  &lt;option&gt;Select&lt;/option&gt;
  &lt;?php
  $con=mysqli_connect("localhost","root","","countries");
  $data=mysqli_query($con,"select * from countries");
  while($row=mysqli_fetch_array($data))
  {
      echo "&lt;option class='con' value=".$row['id'] ."&gt;".$row['name']."&lt;/option&gt;"; 
  }
  ?&gt;
  &lt;/select&gt;
  
  &lt;div id="states"&gt;
  &lt;select&gt;
  &lt;option&gt;Select&lt;/option&gt;
  &lt;/select&gt;
  &lt;/div&gt;
  
  &lt;/form&gt;
  </code></pre>
  
  <p><code>ajax file</code></p>
  
  <pre><code>$(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);
                  }
  
              })
  
          })
  
      })
  </code></pre>
  
  <p><code>country_back.php</code>[to fetch states data]</p>
  
  <pre><code>&lt;?php
  $con_id=$_POST['id'];
  $con=mysqli_connect("localhost","root","","countries");
  $data=mysqli_query($con,"select * from states where country_id='$con' ");
  echo "&lt;select&gt;";
  while($row=mysqli_fetch_array($data))
  {
      echo "&lt;option value=".$row['name']."&lt;/option&gt;"; 
  }
  echo "&lt;/select&gt;";
  
  ?&gt;
  </code></pre>