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>
Enter the codes you’ve made so far
– Phelipe
Friend put the codes to make it easier to help you!
– hugocsl
@Phelipe made it so far...
– Michael Campos
@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.
– Michael Campos