PHP Ajax - combobox state - cities

0

I want to do a select where, in a combobox, I select the state and with that open a new combobox with the respective cities of this state.

I have this divided into two files:

estado.php

//conexao com o banco...
$rs = mysql_query("select distinct loc_uf from local ORDER BY loc_uf ASC");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <script type="text/javascript" src="jquery.js"></script>
     <script type="text/javascript">
     $(document).ready(function(){
        $('#estado').change(function(){
            $('#cidade').load('listaCidades.php?estado='+$('#estado').val());
        });
    });
    </script>
  </head>
   <body>
    <label>Estado:</label>
    <select name="estado" id="estado">
    <?php while($reg = mysql_fetch_object($rs)): ?>
        <option value="<?php echo $reg->id_local ?>"><?php echo $reg->loc_uf?></option>
    <?php endwhile; 
    ?>
    </select>
    <br /><br />
    <div id="cidade"></div>
  </body>
</html>

With this all the states are being listed inside the combobox. Now the file list Cities.php

<?php
//conexao...
$estado = $_GET['estado'];

$rs = mysql_query("select loc_cidade from local where loc_uf ='".$estado."' ORDER BY loc_cidade");

echo "<label>Cidade: </label><select name='cidade'>";
while($reg = mysql_fetch_object($rs)){
    echo "<option value='$reg->loc_cidade'>$reg->loc_cidade</option>";
}
echo "</select>"; 
?>

But the combobox is not being filled in correctly.

What am I doing wrong? How do I capture the selected value in the combo and step as a parameter?

bank table:      local fields: local_id, loc_city, loc_uf

That is, I do not have UF id, only of each city that respectively has a UF.

    
asked by anonymous 18.08.2015 / 15:05

1 answer

1

In the states.php file, the value of each option is the local id field of bd, that is, to find out which state was selected and return the cities you will have to place:

WHERE id_local = $estado

and not loc_uf, as it is in the file.Cities.php.

A small addendum, the mysql_ * functions are obsolete and should be removed from php soon, it is recommended to use mysqli_ * or PDO.

    
19.08.2015 / 03:53