Populating selects of cities and states with AJAX (PHP and jQuery Mobile)

Asked

Viewed 8,910 times

6

I’m riding a webapp with the Jquery Mobile, PHP and AJAX framework.

In this app I have a form with selects of ESTADO and CIDADE, was made an AJAX that when selects the ESTADO, carries the CIDADES according to STATE.

The problem I’m having, and that AJAX only loads the first time, and then no more after selecting the ESTADO for the second time or more.

 <script type="text/javascript">
        $(document).ready(function(){
            $('#estados').change(function(){
                alert ('carrega cidade');
                $('#cidades').load('cidades.php?estado='+$('#estados').val() );

            });
        });

    </script>
<select name="estados" id="estados">
    <option value="0">ESTADO</option>
    <?php
        mysql_connect('localhost','root','');
        mysql_selectdb('proxima-corrida');

       $result = mysql_query("select * from proxc_estado");

       while($row = mysql_fetch_array($result) ){
            echo "<option value='".$row['id_estado']."'>".$row['estado']."</option>";

       }

    ?>
</select>


<select name="cidades" id="cidades">
    <option value="0">Escolha um estado</option>
</select>
<?php

    $idestado = $_GET['estado'];

    mysql_connect('localhost','root','');
    mysql_selectdb('proxima-corrida');

   $result = mysql_query("SELECT * FROM proxc_cidade WHERE estado_cidade = ".$idestado);

   while($row = mysql_fetch_array($result) ){
        echo "<option value='".$row['id_cidade']."'>".$row['cidade']."</option>";

   }

?>
  • You can put console.log('log: ', this.value); on the first line within $('#estados').change(function(){ and check if this is called when you change status again?

  • 2

    Beware of injection of SQL. Because if I use firebug or similar tool to place an element <option value="5; DELETE FROM proxc_cidade; --">pwned</option> in the combobox and select it, its application was already.

  • ok!! I’m still in homologation.. I won’t let the SQL injection @Victor Stafusa go

  • and on the console.log @Sergio is returning UNDEFINED

  • 1

    @Anapaulamoraes 2 questions: 1- the console appears each time the select changes? 2- in HTML the value of these options is right or the value is undefined?

  • then @Sergio, 1- on the console appears yes each time it changes. 2- and in the HTML appears the VALUE of the option, is not appearing more Undefined. Thus, AJAX comes to load the right states and cities. An example, if I select PARANA it loads the CITIES; When I select a second STATE it already stops loading the CITIES of that second selected STATE. I’m guessing it’s some conflict with the Jquery Mobile framework

  • @Anapaulamoraes can put in question a link to the Pastebin with the rendered HTML of the page?

  • @Sergio sorry, I don’t understand. I can send the link by comment?!

  • @Anapaulamoraes yes can be.

  • @Please follow http://www.domadigital.com/proxima-corrida/&#Xa.

  • 2

    @Anapaulamoraes are loading jQuery 1.10 and then 1.3. You can take version 1.3, it will only cause problems...

  • http://answall.com/questions/99107/listar-estados-cidades-e-bairros-em-formul%C3%A1rio-de-cadastro/99133#99133

Show 7 more comments

2 answers

4

I made an example not to depend on programming, only javascript. The file with the cities and states are in https://api.myjson.com/bins/enzld. A query will be made in this file and then populated the other fields. The javascript file I believe is very simple, any question ask that I can explain to you the items that do not understand.

In your case, you can generate this listing as JSON via PHP or even consume a static file like this one from the example.

var estados = [];

function loadEstados(element) {
  if (estados.length > 0) {
    putEstados(element);
    $(element).removeAttr('disabled');
  } else {
    $.ajax({
      url: 'https://api.myjson.com/bins/enzld',
      method: 'get',
      dataType: 'json',
      beforeSend: function() {
        $(element).html('<option>Carregando...</option>');
      }
    }).done(function(response) {
      estados = response.estados;
      putEstados(element);
      $(element).removeAttr('disabled');
    });
  }
}

function putEstados(element) {

  var label = $(element).data('label');
  label = label ? label : 'Estado';

  var options = '<option value="">' + label + '</option>';
  for (var i in estados) {
    var estado = estados[i];
    options += '<option value="' + estado.sigla + '">' + estado.nome + '</option>';
  }

  $(element).html(options);
}

function loadCidades(element, estado_sigla) {
  if (estados.length > 0) {
    putCidades(element, estado_sigla);
    $(element).removeAttr('disabled');
  } else {
    $.ajax({
      url: theme_url + '/assets/json/estados.json',
      method: 'get',
      dataType: 'json',
      beforeSend: function() {
        $(element).html('<option>Carregando...</option>');
      }
    }).done(function(response) {
      estados = response.estados;
      putCidades(element, estado_sigla);
      $(element).removeAttr('disabled');
    });
  }
}

function putCidades(element, estado_sigla) {
  var label = $(element).data('label');
  label = label ? label : 'Cidade';

  var options = '<option value="">' + label + '</option>';
  for (var i in estados) {
    var estado = estados[i];
    if (estado.sigla != estado_sigla)
      continue;
    for (var j in estado.cidades) {
      var cidade = estado.cidades[j];
      options += '<option value="' + cidade + '">' + cidade + '</option>';
    }
  }
  $(element).html(options);
}

document.addEventListener('DOMContentLoaded', function() {
  loadEstados('#uf');
  $(document).on('change', '#uf', function(e) {
    var target = $(this).data('target');
    if (target) {
      loadCidades(target, $(this).val());
    }
  });
}, false);
<div>
  <label for="uf" class="input-label">Estado</label>
  <select name="uf" id="uf" disabled data-target="#cidade">
        <option value="">Estado</option>
    </select>
</div>

<div>
  <label for="cidade" class="input-label">Cidade</label>
  <select name="cidade" id="cidade" disabled>
        <option value="">Cidade</option>
    </select>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  • Fantásico, very good, thanks for the excellent code.

  • Thanks @adventistapr, ;) This is an example of code with pure javascript, I advise you to just use this example to learn and then use a Vuejs framework that would not consume 80% of what was typed there. rsrsr

0

For jQuery ajax to be loaded every time, you can use Jquery delegate method, example:

$(function() {
  $(document).delegate('#estados', 'change', function() {
    var valor = $('#estados').val();
    $('#cidades').load('cidades.php?estado=' + valor );
   });
 });

Browser other questions tagged

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