title: How to populate dropdown list from ajax response?
body: <p>I have a form with 2 dropdown list + 1 hidden field.</p>
  
  <p>First dropdown list is city.</p>
  
  <p>Second dropdown list is district values based on selected city above.</p>
  
  <p>The hidden field will be shown on or off based on particular district value using Jquery.</p>
  
  <p><strong>My problem is:</strong></p>
  
  <p>In the city dropdown list, I have onchange ajax function which help to generate values in the district dropdown list. However, When a particular district value is selected, the hidden field won't show up.</p>
  
  <p><strong>Here is my html form:</strong></p>
  
  <pre><code>&lt;form&gt;
  &lt;select id='main-cat' name='maincat' onchange="sortSubcat(this.value)"/&gt;
  &lt;option value=""&gt;Please select one category&lt;/option&gt;
  &lt;option value="City 1"&gt;City 1&lt;/option&gt;
  &lt;option value="City 2"&gt;City 2&lt;/option&gt;
  &lt;option value="City 3"&gt;City 3&lt;/option&gt;
  &lt;/select&gt;
  &lt;select id='subcat' name='subcat'&gt;
  &lt;option value=''&gt;Please select a district&lt;/option&gt;
  &lt;/select&gt;   
  &lt;div id='morefield' style='display:none'&gt;
   &lt;input type='text' name='option1'/&gt;
  &lt;/div&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p><strong>Here is the onchange ajax function:</strong></p>
  
  <pre><code>function sortSubcat(str)
  {
  if (str=="")
  {
  document.getElementById("subcat").innerHTML="";
  return;
  } 
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200)
  {
  document.getElementById("subcat").innerHTML=xmlhttp.responseText;
  }
  }
  xmlhttp.open("GET","/member/sortsubcat.php?q="+str,true);
  xmlhttp.send();
  }
  </code></pre>
  
  <p><strong>Here is my part of Jquery code to trigger the hidden field if a particular disctrict value is selected:</strong></p>
  
  <pre><code>$("#subcat").change(function(){
  if ($(this).val() == 'district a'){ 
      $("#morefield").css("display","block"); 
  }else{
      $("#morefield").hide();
  }
  });
  </code></pre>
  
  <p><strong>Here is my php file:</strong></p>
  
  <pre><code>&lt;?php
   require_once("../configs/dbconnect.php");
   if (!empty($_GET['q'])){
   $q = basename($_GET['q']);
   $sql="SELECT * FROM subcat WHERE maincat=:q";
   $result = $conn-&gt;prepare($sql);
   $result-&gt;bindParam(':q', $q);
   $result-&gt;execute();
   echo "&lt;option value=''&gt;Please select a district&lt;/option&gt;";
  
   foreach($result as $row)
   {
      echo "&lt;option value='$row[name]'&gt;$row[name]&lt;/option&gt;";  
   }
   }
   else{
   echo "&lt;option value=''&gt;Please select a district&lt;/option&gt;";
   }
   $conn=null;
   ?&gt;
  </code></pre>