Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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
        }
      });
      });
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda