Alert user about JSON response with empty return []

Asked

Viewed 61 times

-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!');
    }

 } 

};

1 answer

0


Good night Igor, I understand from your code that you’re trying this way:

if (resposta == '[]') {
alert('Entrada incorreta!');
}

Your error is that you are comparing response to a string containing '[]', to validate whether the array is empty just replace if (resposta == '[]') for if (resposta.length == 0)

If you still have doubts, follow two links to help you:

How to make a function to tell when an array is empty?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  • 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.

  • 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 the console.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 the console.log(this.responseText);

  • 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!'); }

Browser other questions tagged

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