Empty list after having filled in javascript [duplicated]

0

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.

    
asked by Baker1562 14.02.2018 в 17:41
source

1 answer

1

The AJAX calls are asynchronous, the alert and the end log do not show anything because when those are made the request response ajax (which is the one that fills the list) has not yet arrived. If you want them to show something you should place them at the end of the success function, there is no problem either in the way you show it or in the way you add the elements.

    
answered by 14.02.2018 / 18:02
source