Help with COMBOBOX, Select cities according to chosen state

-1

I'm programming an application in php and I have all the Brazilian states and cities in Mysql bank.

  

In the States table I have: id , nome , uf .

     

In the Cities table I have: id , nome , id_estado .

I created a select for the states and would like that when I clicked on the option of a certain state, the cities of that state appear in the select cities.

Below the code

<?php include_once "conexao.php"; ?>
<html>
    Estado:
    <select name="estado" id="estado">
    <?php 
        $sql = "SELECT 'id','nome', 'uf' FROM estado WHERE 'pais' = 1 ORDER BY 'nome'";
        $res = $mysqli->query($sql);
        while($r = $res->fetch_array()) {
           $r = array_map('utf8_encode', $r);
           $sigla = $r["uf"];
           $nome = $r["nome"];
           $id = $r["id"];

           echo "<option value='$id'> $nome </option>";          
        }

     ?>     

    </select>
  Cidade:
    <select name="cidade" id="cidade">
        <option value="">Cidade</option>
    </select>    
    
asked by anonymous 18.01.2018 / 21:26

2 answers

0

You need popular dynamically select of cities. For this you can use Ajax with pure JavaScript or jQuery.

It works as follows: when selecting a State, the script will send the state code to a PHP page, and this page will make the request to the database of all cities with the State code received, then return an HTML with options that will be inserted in select of cities.

I'll give you a basic example using jQuery, which gets easier, and you can apply it in your code with ease:

Capture value of select of States when selected and call Ajax:

$("#estado").on("change", function(){
    var id_estado = $(this).val();
    $.ajax({
        url: 'cidades.php',
        data: { estado: id_estado }
        dataType: 'html',
        complete: function(result) {
            $("#cidade").html(result);
        }
    });
});

In Ajax above, I send id of the selected state to a PHP page called cidades.php (you can use whatever name you want). This cidades.php page will be responsible for returning to the list of cities in the selected state. This page should contain nothing but PHP codes and the construction of options that will be inserted in select of cities. It is not an ordinary page, with <html><head><body> etc ...

Page cidades.php :

As stated, the only utility on this page is to return options to select cities.

The layout of this page would be:

<?php
$estado = $_GET['estado']; // recebendo o id do Estado enviado pelo Ajax

if(isset($estado) && !empty($estado)){

    // FAZER A REQUISIÇÃO AO BANCO DE DADOS USANDO A VARIÁVEL
    // $estado PARA PEGAR APENAS AS CIDADES COM ESSE id

    // AQUI FAZER UM LOOP NOS RESULTADOS
    while(ENQUANTO HOUVER RESULTADO VINDO DO BANCO){

        echo "<option value='$ID_DA_CIDADE'>$NOME_DA_CIDADE</option>";

    }

}
?>

To call cities on page load, as the first state in select is already selected, you can use jQuery below, which triggers a trigger in select :

$(window).on("load", function(){
    $("#estado").trigger("change");
});

Do not forget to load jQuery into your <head> . You can use this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

SothefulljQueryscriptwouldlooklike:

<script>$("#estado").on("change", function(){
    var id_estado = $(this).val();
    $.ajax({
        url: 'cidades.php',
        data: { estado: id_estado }
        dataType: 'html',
        complete: function(result) {
            $("#cidade").append(result);
        }
    });
});

$(window).on("load", function(){
    $("#estado").trigger("change");
});
</script>
    
18.01.2018 / 23:16
0

The most advisable is to make an ajax request for a page that returns a JSON with the id values and the name of each city for the ID we send. If you use Jquery the code will look something like:

$('#estado').change(function(){
    $('.sair').remove();
    $.ajax({
        method: 'post',
        data: {id: $('#estado').val()},
        url: 'listar-cidades.php',
        success: function(retorno){
            for(i = 0; i < retorno.length; i++) {
                $('#cidade').append('<option class="sair" value="'+retorno[i].id+'" >'+retorno[i].nome+'</option>')
            }
        }
    });
});

What we are doing in this JS code is whenever the ID field changes its state it will send an ajax request to the listar-cidades.php page with the id that the user selected. This code expects a JSON formatted as follows:

[{"id":"1","nome":"Brasília"},{"id":"2","nome":"Taguatinga"},{...}]

Now just build the php script that returns this data by retrieving the id that we send.

    
18.01.2018 / 22:35