Hi, I have the following function in Javascript that is executed when the document loads, I am trying to fill the array lista
but every time I want to show it with a console.log or an alert (except the console.log inside the foreach, there if you show me data) I show it empty, what's my mistake?
$(".content-wrapper").ready(function() {
var vias;
var lista = [];
$.ajax({
url: "views/ajax/OIT.php",
method: "GET",
dataType: "json",
success: function(respuesta) {
console.log("cargo");
if (respuesta == 0) {
console.log("malo");
} else {
console.log(JSON.stringify(respuesta));
vias = respuesta[0];
console.log("Primer console", vias.tipo);
vias.forEach(function(valor, indice, array) {
console.log(
"En el índice " + indice +
" hay este valor (propiedad 'tipo'): " + valor.tipo +
" (desde ['tipo']): " + valor['tipo'] +
" (desde [0]): " + valor[0]
);
lista[indice] = valor.tipo;
console.log("Lista", lista[indice]);
});
}
}
});
alert(lista); //No muestra nada
console.log("Lista", lista[0]); //Aqui tampoco
});
JSON output
[[{"0":"AEREO","tipo":"AEREO"},{"0":"DIRECTO","tipo":"DIRECTO"},{"0":"AEREO","tipo":"AEREO"},{"0":"DIRECTO","tipo":"DIRECTO"},{"0":"MARITIMO","tipo":"MARITIMO"},{"0":"OTROS","tipo":"OTROS"},{"0":"TERRESTRE","tipo":"TERRESTRE"}]]
Console output
I feel that the problem is not JSON because I am iterating it and when I iterate it I insert what I need "AIR, MARITIME, ETC" in the list using lista[indice] = valor.tipo;
that's why after the iteration shows that it brings the "list" in x position, the problem is that when I leave the foreach the list is empty or shows nothing.