load div with ajax without error in replies

0

I have a problem with my ajax script, its function is to get the zipped key and bring its values via the API, but it is presenting an error that I can not solve, typing the full zip it shows exactly the information but they disappear next! then as I am using the .keyup method, pressing any button, the information reappears on the screen and then yes they are fixed, when the cep is incomplete or wrong, it shows me the message "nothing found" and when the cep is correct, it returns the values of the cep, but as I quoted above, when typing the entire zip, it shows all the information and in a fraction of seconds, returns the message "nothing found", then when any key is pressed, it returns to show the data and finally gets fixed.

I have already modified the code several times and I could not find the error, testing with html and ajax of the error, testing with the php file, nothing wrong, so I believe it is my ajax code

$("document").ready(function(){
$(".cep").keyup(function(){


    var cep = $(".cep").val();
    console.log(cep);



            $.ajax({
                url: "content/plugin/cep/cep.php",
                type: "POST",
                data: {cep: cep},
                cache: false,

                success: function(res){

                    if(res.codigo == "1"){  

                    $('.bairro').html('');
                    $('.bairro').html(res.resposta);
                    console.log(res.resposta);
                    return false;
                    }else if(res.codigo == "0"){

                    $('.bairro').html(res.resposta);

                    }
                }

            });

    });


});


cep.php

<?php 

function busca_cep($cep){
    $resultado = @file_get_contents('http://republicavirtual.com.br/web_cep.php?cep='.urlencode($cep).'&formato=query_string');

    parse_str($resultado, $retorno); 
    return $retorno;
}


$ceps = htmlspecialchars($_POST['cep']);
$resultado_busca = busca_cep($ceps);


$log   = $resultado_busca['tipo_logradouro'];
$logr  = $resultado_busca['logradouro'];     
$bai   = $resultado_busca['bairro'];         
$cid   = $resultado_busca['cidade'];         
$uf    = $resultado_busca['uf'];         


if($uf == null){
    $retorno2['codigo'] = 0;
$retorno2['resposta'] = "<div class='fimcep'>Nada encontrado</div>"; 

                         header('Content-type: application/json');
                         echo json_encode($retorno2);
                         return false;
}else{
    $retorno2['codigo'] = 1;
$retorno2['resposta'] = "<div class='fimcep'>$log $logr $bai $cid $uf</div>"; 

                         header('Content-type: application/json');
                         echo json_encode($retorno2);
                         return false;
   }
?>
    
asked by anonymous 12.01.2017 / 23:18

2 answers

1

Ideally, you will use the blur() function of jquery to perform ajax. The function of keyup() is to observe each change of the input, that is, each key entered, so your ajax is making a request each time the user types a letter.

The blur() function is activated only when the user selects "another field" to fill, that is, when he has already finished that field he was in, so the ajax request would only happen once that is when he finishes to type.

You can also check the amount of characters in input before making the ajax request;

$('.input').keyup(function() {
    var length = $(this).val().length;
    // 8 é a quantidade de caracteres minima de um cep
    if (length >= 8) {
        // ... a requisição ajax
    }
});

See working in JsFiddle

    
13.01.2017 / 00:29
0

Good staff, thanks to @Rafael Acioly, it gave me an idea to activate ajax only when the zip field is fully populated, well I made a small change in the code and finished it as follows, the php function of fetching the zip is enabled only if the zip field has exactly 9 digits (counting with the '-' that separates the numbers) from the opposite, does nothing, ajax always sends information but php bar until exactly what it needs, this helped pq if the user erases some zip number, it blocks the fields until the user populates the fields again, and the user can also change the zip without giving any error in the form. I do not know if in Brazil we have ceps outside of the default 99999-999, if we have, my code will not work: (

According to this site Padrao CEP Brasileiro , my code will work!

I'll post the code for the people you need

cepajax.js

$("document").ready(function(){



$(".cep").keyup(function(){

    var leg = $(this).val().length;
    console.log(leg);

    $('.bairro').html('Procurando');
    var cep = $(".cep").val();
    console.log(cep);



            $.ajax({
                url: "content/plugin/cep/cep.php",
                type: "POST",
                data: {cep: cep, leg: leg},
                cache: false,

                success: function(res){

                    if(res.codigo == "1"){  


                    $('.bairro').html(res.resposta);
                    console.log(res.resposta);
                    $('.msg_input').addClass('disableding');
                    return false;
                    }else if(res.codigo == "0"){

                    $('.bairro').html(res.resposta);
                    $('.msg_input').removeClass('disableding');
                    return false;
                    }
                }

            });





});

});

cep.php

<?php 

function search_cep ($ zip) {     $ result = @file_get_contents (' link ' .urlencode ($ cep). '& format = query_string' );

parse_str($resultado, $retorno); 
return $retorno;

}

$ leg = $ _POST ['leg']; $ ceps = $ _POST ['cep'];

if ($ leg == 9) {

$resultado_busca = busca_cep($ceps);

$ log = $ result_search ['log_type']; $ logr = $ resultado_busca ['public place']

$ bai = $ resultado_busca ['bairro'];
$ cid = $ result_search ['city'];
$ uf = $ result_search ['uf'];

if($uf == null){
    $retorno2['codigo'] = 1;
$retorno2['resposta'] = "<div class='fimcep'>Nada encontrado</div>"; 

                         header('Content-type: application/json');
                         echo json_encode($retorno2);

}else{
    $retorno2['codigo'] = 0;
$retorno2['resposta'] = "<div class='fimcep'>$log $logr $bai $cid $uf</div>"; 

                         header('Content-type: application/json');
                         echo json_encode($retorno2);

}

} else {

$retorno2['codigo'] = 1;
$retorno2['resposta'] = "<div class='fimcep'>Nada encontrado</div>"; 

                         header('Content-type: application/json');
                         echo json_encode($retorno2);

}

? >

    
13.01.2017 / 13:47