Tim Biesmans
Tim Biesmans

Reputation: 73

Dynamic country, state, city dropdown select

I have 1 static (country) and 2 dynamic (state and city) dropdown selects.

I'm working with Select2.

For example, The Netherlands has a huge amount of cities for each state. Loading this is hard to work with.

On my userside-page if have following JS:

$(".state").change(function()
    {
        var id=$(this).val();
        var dataString = 'id='+ id;

        $.ajax
        ({
            type: "POST",
            url: "../../get/get_city.php",
            data: dataString,
            cache: false,
            success: function(html)
            {
                $(".city").html(html);
            } 
        });
    });

get_city.php is working and looks like:

if($_POST['id'])
{
    $id=$_POST['id'];

    $stmtc = $admin_home->runQuery("SELECT * FROM city WHERE state_id=:id");
    $stmtc->execute(array(':id' => $id));
    ?><option selected="selected">Selecteer een woonplaats:</option><?php
    while($rowc=$stmtc->fetch(PDO::FETCH_ASSOC))
    {
        ?>
        <option value="<?php echo $rowc['city_id']; ?>"><?php echo $rowc['city_zip']; ?> <?php echo $rowc['city_name']; ?></option>
        <?php
    }
}

I also tried already with the AJAX from select2 seperatly with this code (is also working):

$('.itemName').select2({
        placeholder: 'Select an item',
        ajax: {
          url: '../../get/get_city_ajax.php',
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
            return {
              results: data
            };
          },
          cache: true
        }
      });

get_city_ajax.php looks like:

    $stmtc = $admin_home->runQuery("SELECT * FROM city "
                . "WHERE city_name LIKE '%".$_GET['q']."%' LIMIT 10");
    $stmtc->execute();
        $json = [];
    while($rowc=$stmtc->fetch(PDO::FETCH_ASSOC))
    {
        $json[] = ['id'=>$rowc['city_id'], 'text'=>$rowc['city_name']];
    }


echo json_encode($json);

Now is need a combination of the two to get only the cities from the selected state.

I tried a lot but couldn't get it working.

Upvotes: 2

Views: 6521

Answers (1)

Tim Biesmans
Tim Biesmans

Reputation: 73

This solution works fine for me:

$(".state").change(function()
    {
        var id=$(this).val();
        var dataString = 'id='+ id;
        $('.city').select2({

        placeholder: 'Selecteer een stad',
        ajax: {
          url: '../../get/get_city_ajax.php?'+dataString,
          dataType: 'json',
          delay: 250,
          processResults: function (data) {
            return {
              results: data
            };
          },
          cache: true
        }
      });
      });

Upvotes: 3

Related Questions