First, let's go to the page code where the droplists meet:
State droplist code
<select name="estados" id="estados">
<option value="0">Selecione o estado</option>
<?php
$result = mysql_query("select distinct loc_uf from local ORDER BY loc_uf ASC");
while($row = mysql_fetch_array($result) )
{
echo "<option value='".$row['loc_uf']."'>".$row['loc_uf']."</option>";
}
?>
</select>
On this same page, the droplist code for cities:
<select name="cidades" id="cidades">
<font id="font_cidades"></font>
</select>
Still on this page, the code to search cities with AJAX. For this page, I also used JQuery.
<script type="text/javascript">
$('#estados').change(
function() {
var estado = $('#estado').val(); //Pegando o id do estado
$.ajax({
type: "GET",
url: "AJAX_buscaCidades.php?estado="+estado,
success: function(data) {
$('#font_cidades').html(data); //Se obtivermos sucesso na busca dos dados, atribuímos os dados para o select
}
});
}
);
</script>
And finally, let's go to the AJAX_buscaCidades.php file, which will fetch the cities when the state id is provided.
<?php
$sqlQuery = "select distinct loc_cidade from local WHERE loc_uf = " . $_GET['estado'] . " ORDER BY loc_cidade ASC";
$result = mysql_query();
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['loc_cidade']."'>".$row['loc_cidade']."</option>";
}
?>
Some considerations:
- The code is still 'raw', needs to make changes to queries, fields, etc.
- I suggest using MYSQLI to make queries more securely.
Good luck!