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;
}
?>