1
I’m practicing ajax using the post office API. I did it! But these 2 situations happen:
1- Gets stuck in the Else block, so if I put an invalid zip code after listing a valid one shows nothing, nor msg error that I put to appear, just nothing, only if you put a valid one again.
2- I do not know if it is the way of my rough validation or I have to put something else... that when it shows the data and I want to show another, it does not erase the existing and yes put below what was and so on.
Code:
// Início.
$('form').on('submit', (event) =>{
event.preventDefault();
// Pegando o valor digitado do usuário.
var cep = $('#cep').val();
// Validação do cep.
if(cep.length != 8){
$('p').css({color: "red"})
$('p').html("CEP não existe.");
}else if(isNaN(cep)){
$('p').css({color: "red"});
$('p').html("CEP inválido.");
}else {
// Criando uma URL.
var url = "https://viacep.com.br/ws/" + cep + "/json/";
$.ajax({
type: 'GET',
url: url,
dataType: "JSON",
success: (resp) =>{
for(var i in resp) {
$('#div').append("<h4>"+resp[i]+"</h4>");
}
},
error: (resp) =>{
$('p').css({color: "black"})
$('p').html("Error: ".resp);
}
});
}
})
having nothing to do with your question, my end result would be something like https://jsbin.com/sayozuk/2/edit?html,js,output ... I hope to learn a little bit about :)
– balexandre