Populating a third dropdown with a query result

I have three dropdowns. Based on the option selected in first dropdown i am populating the second dropdown using javascript.

First dropdown

<select id="continent" onchange="secondMenu(this,'country')" >
<option value="1">Asia</option>
<option value="2">Europe</option
</select>

Second dropdown

<select id="country" >
</select>

Third dropdown

<select id="population" >
</select>

My script

<script>
       function secondMenu(ddl1,ddl2){
  var as=new Array('Japan','China');
  var eu=new Array('Germany','France');
 switch (ddl1.value) {
        case 1:
            document.getElementById(ddl2).options.length = 0;
            for (i = 0; i < as.length; i++) {
                createOption(document.getElementById(ddl2), as[i], as[i]);
            }
            break;
        case 2:
            document.getElementById(ddl2).options.length = 0; 
        for (i = 0; i < eu.length; i++) {
            createOption(document.getElementById(ddl2), eu[i], eu[i]);
            }
            break;

   }
     function createOption(ddl, text, value) {
    var opt = document.createElement('option');
    opt.value = value;
    opt.text = text;
    ddl.options.add(opt);
    }
</script>

Now based on the option selected in second dropdown i want to run a mysql query and populate the third dropdown. Any help on how to go about populating the third dropdown.

Upvotes: 0

Views: 164

Answers (2)

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

Use AJAX to send a request to your server and run mysql query. Assuming, you are not using JQuery, pure AJAX looks something like this:

if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function () {
         if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
            var data = xmlhttp.responseText;
            //populating your select
         }
      }
      xmlhttp.open("GET", "yourmethodpath", true);
      xmlhttp.send();
    }

Upvotes: 1

Husman
Husman

Reputation: 6909

Use Ajax, I do something very similar in one of my projects, so heres an example:

$('#product_series_text', $('#product_form')).change(function() {
  var $series = $(this).val();
  // Ajax request to get an updated list of product models
  $.getJSON(
    "<?php echo url::site('product/get_model_like_series'); ?>", 
    { series: $series },
    function(data) {
      $("#product_model", 
        $('#product_form')).form_utils('replaceOptions', data);
    });
});

Theres a lot of jQuery there, but the idea is to have an eventlistener for a change in one dropdown, then fire off an Ajax query (which polls the database and sends back a Json list of results), which then create a dropdown list for us (just the options are changed as the dropdown list already exists)

Upvotes: 1

Related Questions