2

I need to get the value of the selected items on the first dropdown because on the second drop down the list that will be shown will depend on the value from the first drop down. Here's my coding. By the way I am using PHP.

In here I am displaying the list of region, then when region is already selected the province that are only under that region should be displayed in the second drop down.

First drop down:

<p><b>Region:</b>
<select class="w3-select" name="region" id="region_value"     
onChange="myFunction()" required>
<option value="">--- Select Region ---</option>
<?php 
    $Region = $FormModel->RegionList();
    foreach($Region as $RegionList) {
?>
<option id="option" value="<?php echo $RegionList['region_code']?>"><?php   
echo $RegionList['region_name'] ?> </option> </p>
<?php } ?>
</select>

Second drop down:

<p><b>Province:</b>
<select class="w3-select" name="province" id="demo"  required>
<option value="">--- Select Province ---</option>
<?php 
    $Province = $FormModel->ProvinceList();
    foreach($Province as $ProvinceList) {
?>
<option value="<?php echo $ProvinceList['prov_code']?>"> <?php echo   
$ProvinceList['prov_name'] ?> </option> </p>
<?php } ?>
</select>

I have a java script here getting the value of the selected items but I don't know how to pass it as an attribute to set the value as the region code. I have a setter and getter in which I will set first the region code and in my query I am getting the value of the region code. But it's not working.

<script>
function myFunction() {
var x = document.getElementById("region_value").value;
$FormModel = new Form(x);

}
</script>

Here's my query where I get the list of province.

public function ProvinceList(){

    $region = $this->getRegion();
    $sql = "SELECT prov_code,psgc_prv, prov_name FROM lib_provinces WHERE  
    region_code='$region' ORDER BY prov_name"; 


    $this->openDB();
    $this->prepareQuery($sql);
    $result = $this->executeQuery();
    $recordlist = array();
    $trash = array_pop($recordlist);

    foreach($result as $i=>$row){

                $row_data = array(
                    "prov_code"=>$row["prov_code"],
                    "psgc_prv"=>$row["psgc_prv"],
                    "prov_name"=>$row["prov_name"]
                );
            $recordlist[$i] = $row_data;
    }
    $this->closeDB();
    return $recordlist;

}

I would be a great help if someone can answer me in this work around.Thanks!

Phoenix
  • 51
  • 1
  • 7
  • Remove id form options, although its repeating , id should be unique. – Niklesh Raut May 18 '16 at 03:17
  • Google for php+ajax to submit form – Niklesh Raut May 18 '16 at 03:20
  • I have removed the other id in option. I just forgot to remove it because i have done many edition in my code getting the right way to do it. However, it still not working. About ajax I am not that much knowledgeable with this, can you at least give me a sample on how to do it on my code?thanks. – Phoenix May 18 '16 at 03:32

2 Answers2

1

If fetching all the provinces at once is an option you should do this via javascript.

You need to have all the items in a javascript variable and fill you select with these values. OnChange you should filter the values using only the ones that applies

<script>

var optionItems;    
var values = <?php echo json_encode($ProvinceList) ?>;
refreshOptions(values);

function refreshOptions(listItems, x) {
    x = x || 0;
    var sel = document.getElementById('demo');
    sel.innerHTML = "";
  for(var i = 0; i < listItems.length; i++) {
        if ((x == 0) || (listItems[i].psgc_prv == x)) {
        var opt = document.createElement('option');
        opt.innerHTML = listItems[i].prov_name;
        opt.value = listItems[i].prov_code;
        sel.appendChild(opt);
      }
  }
}

function myFunction() {
    var x = document.getElementById("region_value").value;

    refreshOptions(values, x);
}
</script>

The second drop down would be just

<select class="w3-select" name="province" id="demo"  required>
</select>

This implies stop filtering in the php query to the database

 $sql = "SELECT prov_code,psgc_prv, prov_name FROM lib_provinces ORDER BY prov_name"; 

See this feedle with a working example (without the php) https://fiddle.jshell.net/7k18euhw/3/


Edit since there is a new request of having another select level

If you have a lot o municipalities the approach of getting all of them in the same way as in Provinces is not a good idea. In that case you will need use ajax to fetch them.

This is what you need to do:

  • Having an accesible url that receives a province id as param and returns a json with the list of municipaties

Depending on how are you using php are many ways to do this for example if you have a framework you should have a controller is is just vainilla php should be something like this.

mun-list.php

echo json_encode($FormModel->ProvinceList($_GET['prov_id']));
  • get the onChange event for provinces (in the same way that you are doing with regions) and make a ajax call to the service that you jus created.

As already Kaja suggested you should use jquery to do this (http://jquery.com/)

function onProvChange() {
        var prov_id = $("#prov_select").val();
        $.ajax({
            url: 'mun-list.php?prov_id='+prov_id, 
            type: 'GET',
            success: function(data) {
                //without a lot of detail this should populate in the way you did before
                refreshMunicipalities(data);
            }
        });

}

You can do it without it but is harder, take a look at this post.How to make an AJAX call without jQuery?

Community
  • 1
  • 1
dminones
  • 2,236
  • 20
  • 21
  • in the second drop down the code will be just like this?? i will remove the foreach loop inside? – Phoenix May 18 '16 at 03:50
  • That's because the population will be done via javascript: refreshOptions(values); Note that this line is called when the page loads and populates with all the elements – dminones May 18 '16 at 03:58
  • I have just copied your code then change the select and my query but it doesn't work. Is there anything I should add here?Though, I added also $ProvinceList = $FormModel->ProvinceList(); this code to get the list of provinces. – Phoenix May 18 '16 at 04:05
  • you should check your generated javascript to see if the php variable is being translated to a variable like this one: var values = [{"prov_code":1,"psgc_prv":1,"prov_name":"prov one, reg 1"}, {"prov_code":2,"psgc_prv":3,"prov_name":"prov two, reg 3"}, {"prov_code":3,"psgc_prv":2,"prov_name":"prov three, reg 2"}, {"prov_code":4,"psgc_prv":3,"prov_name":"prov four, reg 3"}]; – dminones May 18 '16 at 04:13
  • also you should check at your developer console to see any javascript errors and to debug – dminones May 18 '16 at 04:14
  • hi the code is now working :) I just changed the psgc_prv into region_code because it is their linking. thanks for this! my next problem now which I'm working now is the 3rd dropdown which depends on the value of the selected item of the 2nd dropdown. the 3rd dropdown is for municipality, i have tried creating another function for municipality just like the code you gave me but it doesn't work. what would be the possible way to do this? i know it's too much but it would really be a great help for me since i am just new to ajax coding. thanks much! – Phoenix May 19 '16 at 02:45
  • great! i'm glad this worked. About municipality how many of them are/will potencially be in the db? – dminones May 19 '16 at 04:26
  • Yes. I'm glad too :)I don't know the exact rows of municipality that will be fetched from db, i just need to display all the municipality under that province. – Phoenix May 19 '16 at 05:28
0

By using Ajax you can fix. I have used jquery and php

For an example

$("#region_value").change(function() {
    region_value= $("#region_value").val();
        $.ajax({
            url: 'ProvinceList URL', 
            data:  { region_value: region_value },
            type: 'POST',
            success: function(data) {
                var json = JSON.parse(data); \\ I have used JSON to parse data
                $('#demo').empty(); // clear the current elements in select box
                $('#demo').append('<option value=>Select province</option>');
                for (row in json) {
                    $('#demo').append('<option value='+json[row].prov_code+'>'+json[row].prov_name+'</option>');
                }
            }
        });
    });
Konstantin
  • 57
  • 1
  • 8
Kaja Mydeen
  • 585
  • 1
  • 7
  • 13