First, let’s go to the code of the page 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 code of the city droplist:
<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, you need to make changes to queries, fields, etc.
- I suggest using MYSQLI to make queries more safely.
Enjoy!
It is not giving error this way, but when selecting the state does not appear anything in the combobox cities. The queries are correct and I imported into the <head> or <script type="text/javascript" src="jquery.js"></script>.
– PHP developer
@Phpdeveloper, I suggest including Avascripts in the footer and not in the header. maybe that’s it
– Guilherme
Nothing yet... how can I test if $_GET['status'] is capturing the selected state and is not coming blank?
– PHP developer