load div with ajax without error in the answers

Asked

Viewed 192 times

0

I have a problem with my ajax script, its function is to take the typed zip code and bring its values via API , however it is presenting an error that I cannot solve, by typing the complete zip code it shows exactly the information but they disappear then! then as I am using the method. keyup, when 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 mentioned above, When you type the whole zip code, it shows all the information and in a fraction of seconds, it returns the message "nothing found", then when you press any key, it returns to show the data and finally it is fixed.

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

$("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;
   }
?>
  • Voce is running off a server when testing only in Ajax?

  • I just ran the php file and returned the data right, but when together with ajax and html, this bug

2 answers

1


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

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

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 on Jsfiddle

  • intendo man, however there is no other field to be filled in until the answer returns, it has only 1 field 'cep' , when this field returns ok, there releases the other fields, otherwise, all other fields are disabled, there is how I put Blur() be activated only when the input is with a certain number of characters?

  • I could also put a button with the click() function but I would like to leave as dynamic as possible, well buttons

  • I could also take out the keyup() and put some sort of character counter, for example, if field. cep has 8 characters, then it activates ajax, and so I think I can stop giving error, because I will only make a query, but I have no idea how to do this function, I’m searching now

  • 1

    @Jonnysj. the blur it will work when the user changes the focus of the input; if he clicks off (not necessarily in another input) will activate, if he gives tab and etc, I made a change as per your comment.

  • I tested it with Blur and it worked! then really the problem is with the keyup, but still I needed another method without click, because the Blur only works if I fill the box and click anywhere else, other than the keyup filling the box automatically, if you have to click, and better put a button to facilitate understanding for the user.

  • @Jonnysj. you can use the keyup as in the example I put.

Show 1 more comment

0

good people, thanks to @Rafael Acioly, he gave me an idea to activate ajax only when the cep field is fully filled, well I made a small change in the code and finished as follows, the php function of fetching the cep is enabled only if the cep field has exactly 9 digits ( counting the '-' that separates the numbers ) from the other way around, does nothing, ajax always sends the information but php bar until it has exactly what it needs, This helped until pq if the user deletes some number of the zip code, it blocks the fields until the user fills the fields again, and the user can also change the zip code without giving any error in the form. well I don’t know if in Brazil we have strains outside the standard 99999-999, if we have, my code won’t work :(

according to this website Padrao CEP Brasileiro, my code will work!

I’ll post the code to the people who need it

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 busca_cep($cep){ $result = @file_get_contents('http://republicavirtual.com.br/web_cep.php?cep='.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 = $resultado_search['street type']; $logr = $resultado_busca['logradouro'];
$Bai = $resultado_search['neighborhood'];
$Cid = $resultado_search['city'];
$Uf = $resultado_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);

}

?>

Browser other questions tagged

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