-1
I am already more than 15 hours straight tried a simple solution but for me it is very difficult, please help me! I have a code that performs a query and when the input is incorrect the return is [] I need to display an incorrect entry alert but I’ve been trying everything since yesterday and I couldn’t, I’m sorry, I’m a layman, but I’m learning. Thank you very much, follow the code:
Function searchPorCpf(){
const cpf = document.getElementById("cpf").value;
const mesAno = buscaMes();
const url = "http://localhost/busca-dados/cpf?codigo="+cpf+"&anoMesReferencia="+mesAno+"&anoMesCompetencia="+mesAno+"&pagina=1";
var ajax = createCORSRequest('GET', url);
if (!ajax) {
throw new Error('CORS not supported');
}
ajax.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText);
let resposta = JSON.parse(this.responseText)[0];
const valor = resposta.valor;
const nome = resposta.titular.nome;
const cpf = resposta.titular.cpfFormatado;
document.getElementById("pcpf").innerHTML = cpf;
document.getElementById("pessoas").innerHTML = nome;
document.getElementById("pvalor").innerHTML = valor;
if (resposta == '[]') {
alert('Entrada incorreta!');
}
}
};
Good night! Thank you so much for answering my question Jeoronei, I changed the code and it didn’t work, it turns out that when the input is invalid the json answer displays nothing but a [] so I’m not able to find the solution, I am so far trying since yesterday.
– Igor
Good evening Igor, I think I understand your problem now, you said
quando a entrada é inválida a resposta do json não exibe nada além de um []
, That means it’s taking place in theconsole.log(this.responseText)
. Then it is showing error because responseText is empty and you are trying to access the [0] position of it. In this case you just carry out the validation before assigning. Try the following test:if (this.responseText.length == 0) {
 alert('Entrada incorreta!');
 }
below theconsole.log(this.responseText);
– Jeoronei Ribinski
Good morning @Jeoronei Ribinski, thank you so much for helping me, it worked with the following code
if (this.responseText.length < 3) { alert('Entrada incorreta!'); }
– Igor