Popular select of countries and states with php mysql ajax

0

I have 2 selects: #pais and #status.

I want you to populate the state with only the states of that country, which are stored in a mysql table:

tabela_paises
id|pais
 1|brasil

tabela_estados
id|idpais|estado
 1|  1   |São Paulo

the country select already has a query, the values of the country_table

$db =& JFactory::getDBO();
$db->setQuery("SELECT pais FROM tabela_paises ORDER BY pais ASC");
$results = $db->loadObjectList();
$items[] = "- Nenhum -";
foreach ($results as $res){
$items[] = $res->pais;
}
return implode("\n",$items);

But for the state I do not know how to do to get the id of the country as a filter, I thought of something like below, but in this case the id is fixed, it needs to be dynamic

$db =& JFactory::getDBO();
$db->setQuery("SELECT estado FROM tabela_estados WHERE idpais = 1 ORDER BY estado ASC");
$results = $db->loadObjectList();
$items[] = "-  Nenhum -";
foreach ($results as $res){
$items[] = $res->estado;
}
return implode("\n",$items);
    
asked by anonymous 29.03.2018 / 17:26

1 answer

0

When you select a country, you need to query with ajax on the file that you select in the database to list the states.

In this file I left the id of parents as $_POST['pais'] , but then you adapt to the way you are defining the type of request. Then you return these results to ajax through json_encode .

Finally you go through this data with a for and add them within select states.

PHP

$db =& JFactory::getDBO();
$db->setQuery("SELECT estado FROM tabela_estados WHERE idpais = $_POST['pais'] ORDER BY estado ASC");
$results = $db->loadObjectList();

foreach ($results as $res) {
    $estados[] = array(
      'id'  => $res->id,
      'nome' => $res->estado,
  );
}

return json_encode($estados);

JAVASCRIPT

$(document).ready(function() {
  $('#pais').on('change', function() {
      var pais = $(this).val();

      $.ajax({
        url: 'estados.php,
        type: 'POST',
        data: { pais : pais },
        dataType: 'json',
        success: function(data) {    
          var options = '<option value=""></option>';

          for (var i = 0; i < data.length; i++) {
            options += '<option value="' +
              data[i].id + '">' +
              data[i].nome + '</option>';
          }

          $('#estados').html(options);
        }
    });
  });
});
    
29.03.2018 / 17:51