title: How to list bootstrap dropdown item values from database using ajax call?
body: <p>I am having a Bootstrap dropdown in my HTML which when clicked should list values from postgres database through AJAX request</p>
  
  <pre><code>&lt;div class="dropdown"&gt;
    &lt;button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"&gt;Region/Country
      &lt;span class="caret"&gt;&lt;/span&gt;
    &lt;/button&gt;
    &lt;ul class="dropdown-menu"&gt;
      &lt;li&gt;
        &lt;a href="#"&gt;&lt;/a&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>This is my PHP service code which gets called by AJAX when the dropdown is clicked:</p>
  
  <pre><code>$result = pg_query($dbh, "SELECT country from countries");
  
  if (!$result) {
    echo "An error occurred.\n";
    exit;
  }
  $features = array();
  
  while ($row = pg_fetch_array($result)) {
    $features[] = array("country" =&gt; array($row[0]));
  }
  
  $result_feature = $features;
  
  echo json_encode($result_feature);
  </code></pre>
  
  <p>I had tried something like below</p>
  
  <pre><code>$(".dropdown-toggle").dropdown({
                  source: function (request, response) {
                       $.ajax({
                           url: 'KFRI_Service.php',
                           dataType: 'json',//since you wait for json
                           data: {
                              'service': 'dropdown'
                          },
                           success: function(json){
                          //now when you received json, render options
                              $.each(json, function(i, option){
                                  var rendered_option = '&lt;li&gt;&lt;a href="#"&gt;'+ option.country +'&lt;/a&gt;&lt;/li&gt;';
                                  $(rendered_option).appendTo('.dropdown-menu');
                              })
                          }
                      })
  
                  }
              })
  </code></pre>
  
  <p><a href="http://i.stack.imgur.com/ygRx6.png" rel="nofollow">current dropdown</a></p>