JSON Zip Code Problem with States and Cities Select

1

Good afternoon,

I have a problem with my select states and cities.

When I type a ZIP it fills in the fields automatically, I can already fill up to the State even though it is a select and better yet not needing to abbreviate the > States in "option value", but the city is not selected, you see: it is displayed in the field below, or the link between city and state is working, but it does not return the city that was received from the script of CEP, below the codes below:

cep.js

$("#cep_res").blur(function() {

var url = "http://cep.republicavirtual.com.br/web_cep.php";
var cep = $(this).val();

 $.ajax({
    type: "GET",
    dataType: 'json',
    data: {'cep': cep, 'formato': 'json'},
    async: false,
    url: url,
    success: function(response) {

        if (response.resultado === '1') {

            $("#bairro_res").val(response.bairro);
            $("#logradouro_res").val(response.logradouro);

            var uf = response.uf;
            $("select#estado_ress option").each(function() {
                this.selected = (this.text === uf);
            });

            var cidade = response.cidade;
            $("select#cidade_ress option").each(function() {
                this.selected = (this.text === cidade);
            });

            $("#estado_ress").trigger("change");

        }

    }
 });

});

form.php

        <label>Estado <span>*</span></label>
        <select class="classic" name="estado_res" id="estado_ress">
            <option value="0">Selecione</option>
            <?php
                $q = "SELECT * FROM estado ORDER BY nome";
                $g = connect($q);
                while($e = mysql_fetch_assoc($g[0])){
                    echo '<option value="'.$e['id'].'">'.$e['uf'].'</option>';
                }
            ?>
        </select>
        <script>
            $(document).ready(function(){
                $('#estado_ress').change(function(){
                    var param = $(this).val();

                    $.post("../escola/busca_cidade.php", { est: param }, function(valor){
                            $("#aqui_cidadec").html(valor);

                        }

                    );
                });
            });
        </script>
        <div id="aqui_cidadec">
            <label>Cidade <span>*</span></label>
            <select class="classic" name="cidade_res" id="cidade_ress" style="text-transform:none !important;">
                    <option value="0">Selecione</option>
            </select>
        </div>

search.php

<?php

require_once('./lib/classes/conexao.php'); 
require_once('./lib/functions/functions.func.php'); 
require_once('./lib/classes/mysql.class.php');
if(!empty($_REQUEST['est'])){

    $q = "SELECT * FROM cidade WHERE estado = '".$_REQUEST['est']."'";
    $g = connect($q);
    echo '<label>Cidade <span>*</span></label>';
    echo '<select class="classic" name="cidade_res" id="cidade_ress">
                <option value="0">Selecione</option>';

    while ( $l = mysql_fetch_assoc($g[0]) ) {
        echo '<option value="'.$l['id'].'">'.$l['nome'].'</option>';
    }
    echo '</select>';
} else { ; }
?>

At the end of the form.php I have the following script:

<script src="<?php echo $url_site; ?>lib/js/cep.js" type="text/javascript"></script>

Anyone who has suggestions of what can be done or some mistake I've made, you can comment there!

    
asked by anonymous 17.03.2018 / 18:22

1 answer

0
  

It is not recommended to use async: false . Here's why in this question .

This is because you want to get the city before processing Ajax that exchanges the state and populates the select of cities, so the code does not know which option to select.

You need to make the loop ...

$("select#cidade_ress option").each(function() {
    this.selected = (this.text === cidade);
});

... after select of cities are populated. Do the following: send the value of the city as a parameter of trigger to Ajax of states and place the loop in that Ajax:

var cidade = response.cidade;
$("#estado_ress").trigger("change", cidade);

And in Ajax of States (event change ), get the value cidade sent by trigger and loop:

$('#estado_ress').change(function(e, cidade){
   var param = $(this).val();

   $.post("../escola/busca_cidade.php", { est: param }, function(valor){
      $("#aqui_cidadec").html(valor);

      $("select#cidade_ress option").each(function() {
         this.selected = (this.text === cidade);
      });

   });
});

In short, CEP's Ajax would look like this:

$.ajax({
    type: "GET",
    dataType: 'json',
    data: {'cep': cep, 'formato': 'json'},
    async: false,
    url: url,
    success: function(response) {

        if (response.resultado === '1') {

            $("#bairro_res").val(response.bairro);
            $("#logradouro_res").val(response.logradouro);

            var uf = response.uf;
            $("select#estado_ress option").each(function() {
                this.selected = (this.text === uf);
            });

            var cidade = response.cidade;

            $("#estado_ress").trigger("change", cidade);

        }

    }
 });

});

And that of the States like this:

$('#estado_ress').change(function(e, cidade){
   var param = $(this).val();

   $.post("../escola/busca_cidade.php", { est: param }, function(valor){
      $("#aqui_cidadec").html(valor);

      $("select#cidade_ress option").each(function() {
         this.selected = (this.text === cidade);
      });

   });
});

Edit

Function to remove accents from city names:

function remAcentos(p){

   var acc = {
      'â': 'a', 'à': 'a', 'ã': 'a', 'â': 'a', 'á': 'a',
      'é': 'e', 'ê': 'e',
      'í': 'i',
      'ó': 'o', 'õ': 'o', 'ô': 'o',
      'ú': 'u'
   }

   return p.replace(/[áàãâéêíóõôú]/g, function(m){
      return acc[m];
   });

}

To use the function, include the cidade variable by calling it:

$('#estado_ress').change(function(e, cidade){

      cidade = remAcentos(cidade); // AQUI REMOVE OS ACENTOS

      $("select#cidade_ress option").each(function() {
         this.selected = (this.text.toLowerCase() === cidade);
      });

});

It's also interesting to add a toLowerCase() here:

this.selected = (this.text.toLowerCase() === cidade);

Because it may be that some city can come with a capital letter accented. With toLowerCase() this problem is bypassed.

    
17.03.2018 / 20:11