Help with COMBOBOX, Select cities according to chosen state

Asked

Viewed 1,681 times

-1

I am programming a php application and I have all the states and cities of Brazil in the Mysql database.

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

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

I created a select for states and I would like when I click on the option for a particular state, to show the cities in the select of 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>    
  • Enter the codes you’ve made so far

  • 1

    Friend put the codes to make it easier to help you!

  • @Phelipe made it so far...

  • @hugocsl as the value in the first select corresponds to the id of each state, what I thought to do was to capture the value of the selected option, and put in the sql Where that would list the cities in the other select. But I have no idea how to do that.

2 answers

0

The most advisable is to make an ajax request to a page that returns a JSON with the id values and the name of each city related to the ID we send. If you use Jquery the code will be 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 field with ID changes its state it will send an ajax request to the page listar-cidades.php 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 recovering the id that we send.

  • I’m starting programming now, my knowledge is limited to html, css and PHP... This type of tip helps greatly to broaden my field of view! Thank you!!

  • Take a look at Javascript and ajax requests. These are essential technologies in web development. Jquary is nothing more than a javascript framework.

0


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

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

I’ll give you a basic example using jQuery, which makes it easier, and you can apply it to your code with peace of mind:

Capture the value of select 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 the Ajax above, I send the id State selected for a PHP page called cidades.php (you can use the name you want). This page cidades.php will be responsible for returning the list of cities of the selected state. This page should contain nothing other than PHP codes and the construction of options to be inserted into select cities. It is not a common page, with <html><head><body> etc....

Page cidades.php:

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

The scheme 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 the cities in the page load, because the first select already comes selected, you can use the jQuery below, which fires a Trigger in the select:

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

Don’t 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>

Then the full jQuery script would be:

<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>
  • Friend, on my machine the ajax is not sending the state ID to the page that returns the cities... I tested the same code on a friend’s machine and it worked perfectly.. Do you have any idea what it might be like?

  • Ajax soh works on server. If you try the local machine, it is not certain.

  • @Michaelcampos That would be it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.