criticise error when CEP is invalid (via CEP )

Asked

Viewed 627 times

0

Hello!

I am using the code below to get address through the CEP informed.

It works, but when typing an invalid zip code or 0000000, I get the return {"erro":true}. How can I turn this return into an Alert with the code below:

	console.log("webservice cep");
	
	$("#numero").attr("readOnly", true);
	$("#complemento").attr("readOnly", true);
	//var lastCepCheck = '';
	var ultimo_cep = '';
	document.getElementById('cep').addEventListener('keyup', function() {
	    //Impede inserir algo alem de Números
	    //this.value = this.value.replace(/[^0-9]/, "");

	    //Pega apenas os números
	    var cep = this.value.replace(/[^0-9]/, "");

	    //Só pesquisa se tiver 8 caracteres e o ultimo cep pesquisado seja diferente do atual.
	    if (cep.length != 8 || ultimo_cep == cep) {
	        return false;			
	    }
	    ultimo_cep = cep;

	    ajax = new XMLHttpRequest();

	    var url = "http://viacep.com.br/ws/" + cep + "/json/";
	    ajax.open('GET', url, true);
	    ajax.send();

	    ajax.onreadystatechange = function() {
			//console.log(ajax.status);
	        if (ajax.readyState == 4 && ajax.status == 200) {
	            var json = JSON.parse(ajax.responseText);				
	            console.log(ajax.responseText);
				if (json == "{erro: true}"){
					alert("erro");
				}
				else {
				$("#logradouro").val(json.logradouro);
				$("#bairro").val(json.bairro);
				$("#cidade").val(json.localidade);
				$("#uf").val(json.uf);
				$("#numero").attr("readOnly", false);
				$("#complemento").attr("readOnly", false);
				$("#numero").focus();
	            }
	        } 
	    }
	});

2 answers

2


There may be other, more simplified methods, but in this way it also works. Just convert to String the return of the error that is in JSON and do the check:

if (JSON.stringify({erro: true}) == '{"erro":true}')
  alert("erro");

Edited:

if (JSON.stringify(json) == '{"erro":true}')
  {alert("erro");}
  • I get this: Uncaught TypeError: json.stringify is not a function
 at XMLHttpRequest.ajax.onreadystatechange

  • If you uncomment the line //console.log(ajax.status);, what code shows? If it is different from 200, it will not even go through the error check.

  • displays code 200

  • Can you find the name of the property that returns the error? In this case, just replace. if (json.propriedade.stringify({erro: true}) == '{"erro":true}')
 alert("erro");

  • Also try to: if (JSON.stringify(json) == '{"erro":true}') alert("erro");

  • Perfect, look how it turned out! if (JSON.stringify(json) == '{"erro":true}') {alert("erro");}

  • Update the reply to mark it! Thanks!!

  • https://answall.com/posts/215227/revisions

Show 3 more comments

1

You can use the function hasOwnProperty() to check if there is the "error" Indice in the value returned by API;

var json = JSON.parse(ajax.responseText);
if (json.hasOwnProperty('error')) {
    console.log(json.error);
}
...

Browser other questions tagged

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