I have a variable called "rela" which retrieves data from a query if there is a match with the database table (I have already tried this and it works). I do this in a fetch()
promise, now I want to change the code I have since I have thought of a conditional to check if the variable is NULL
.
This is what I have
fetch('prdSimilares.php',{
method: 'POST',
body: data
})
.then(res => res.json())
.then(dataS => {
let rela = JSON.parse(JSON.stringify(dataS));
let html = ' ';
for (let i = 0; i < rela.length; i++) {
html += `<div class="item">
<img class="img-trj-prodRela" src="${rela[i].foto}" alt="${rela[i].nombre}" id="${rela[i].categoria},${rela[i].subcategoria},${rela[i].nombre},${rela[i].codigo},${rela[i].id_cat}" onclick="javascript: clave()">
</div>`;
}
...
...
});
what I have tried: first I commented on the for loop and did an console.log(typeof rela)
I get that rela is an object, then I did console.log(rela)
to see what was obtained and the response was a [null]
; already with this I tried to put a
if (rela === null){
console.log('vacio');
//ocultar contenedor
} else {
for (let i = 0; i < rela.length; i++) {
...
...
}
}
But the "empty" message was not shown in the console and I did the for loop code, I also tried using the operator ==
and in the same way the message was not shown and the loop was made.
I don't want to leave you without this conditional since the error in this part would remain in the console. How can I check if the variable is null?