Popular select from countries and states with php mysql ajax

Asked

Viewed 667 times

0

I have 2 selects: #parents and #status.

I want that when selecting the country, it populates the state only with the states of that country, which are written in a mysql table:

tabela_paises
id|pais
 1|brasil

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

the country select already contains 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 do not know how to get the country id as 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);
  • How are you doing to send the information to the server? Is the whole page loaded or by ajax? You need to define how the status id should arrive per parameter in the request.

1 answer

0

When selecting a country, you need to make an appointment with ajax in the file you make the select in the bank to list the states.

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

Finally you run through that data with a for and adds them into the select of 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);
        }
    });
  });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.