Error showing json data

0

I have this code:

<script type="text/javascript">
var direcciones = [];

function getDirecciones()
{
    $.ajax({
        url: "getDireccionesJSON.php",
        success: function (data)
        { 
            if (data != 0)
            {
                var datos = jQuery.parseJSON(data);

                for(var i = 0; i < datos.length; i++)
                {
                  var dato = { "sitio" : datos[i]["sitio"], "direccion" : datos[i]["direccion"] }   
                  direcciones.push(dato);
                }
            }
            else
                alert("No se pudo leer el json");
        }
    });

    for(var i = 0; i < direcciones.length; i++)
       document.write("Sitio: " + direcciones[i]["sitio"] + " Dirección: "  + direcciones[i]["direccion"] + "<br>");
}

getDirecciones();
</script>

Why, when I get to the second cycle for to go through the array, does it indicate that there are no elements, if it is assumed that in the first cycle for insert in that array the data that came in the json ??

    
asked by Jorge Alonso 09.11.2018 в 20:05
source

3 answers

0

See my answer in the link that @AngelOropeza has given you in the comments for more detailed information. To understand this quickly, think of two parallel worlds:

  • One executes the "normal" lines
  • The other executes callbacks and promises ( asynchronous processes ).

In world one, all the code is executed that is not a callback or a promise in the order in which they are described , while in world two, in parallel, the callbacks and promises . When world one executes for , world two is "waiting" for the server to return the data (in the callback); that is, the function that you pass to success is still not resolved . It is for this reason that directions are empty.

What is the solution?

As it is, you can pass a callback to getDirecciones so that it is executed once the addresses are ready:

function getDirecciones(cb)
{
    $.ajax({
        url: "getDireccionesJSON.php",
        success: function (data)
        {
            if (data != 0)
            {
                const direcciones = []
                const datos = jQuery.parseJSON(data);

                for(var i = 0; i < datos.length; i++)
                {
                  const dato = { "sitio" : datos[i]["sitio"], "direccion" : datos[i]["direccion"] }   
                  direcciones.push(dato);
                }
                cb(direcciones)
            }
            else
                alert("No se pudo leer el json");
        }
    });
}
  

Note: You can simplify the code as follows:

const direcciones = datos.map(({ sitio, direccion }) => ({ sitio, direccion })
cb(direcciones)

And finally, you call the function like this:

getDirecciones((direcciones) => {
    for(var i = 0; i < direcciones.length; i++) {
           document.write("Sitio: " + direcciones[i]["sitio"] + " Dirección: "  + 
           direcciones[i]["direccion"] + "<br>");
    }
});
    
answered by 09.11.2018 / 20:39
source
1

you can do it with fetch () functions:

fetch('getDireccionesJSON.php')
  .then(function(response) {
    // cuando termine la peticion retornara los datos
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
    // ya aqui a terminado y tienes los datos disponibles y puedes trabajarlo como gustes
  })
.catch(function(error) {
// si ocurre un error en la peticion!
  console.log('Hubo un problema con la petición Fetch:' + error.message);
});;

or improving your example:

var direcciones = [];
var content="";
function getDirecciones()
{
   var res= $.ajax({
        url: "getDireccionesJSON.php",
       dataType: "json",
    });


    return res;

}

getDirecciones().done(function(response){
            if (data != 0)
            {
                var datos = jQuery.parseJSON(data);

                for(var i = 0; i < datos.length; i++)
                {
                 content += 'Sitio: ${direcciones[i]["sitio"]} Dirección: ${direcciones[i]["direccion"]} <br>';
                }
            }
            else
                alert("No se pudo leer el json");
        }
       document.write(content);

});
    
answered by 09.11.2018 в 20:35
0

It happens that when you make an ajax request you are really imaginatively opening a new tab in the browser and accessing a URL, the time it takes for the server to respond is reflected in real life, but javascript does not wait for this to end process and continue while your variable continues until the server responds and the request is completed.

In order for your code to work, you just have to put the iteration in success (which is the function that is called once the server responds),

<script type="text/javascript">
var direcciones = [];

function getDirecciones()
{
    $.ajax({
        url: "getDireccionesJSON.php",
        success: function (data)
        { 
            if (data != 0)
            {
                var datos = jQuery.parseJSON(data);

                for(var i = 0; i < datos.length; i++)
                {
                  var dato = { "sitio" : datos[i]["sitio"], "direccion" : datos[i]["direccion"] }   
                  direcciones.push(dato);
                }
    for(var i = 0; i < direcciones.length; i++)
       document.write("Sitio: " + direcciones[i]["sitio"] + " Dirección: "  + direcciones[i]["direccion"] + "<br>");

            }
            else
                alert("No se pudo leer el json");
        }
    });

}

getDirecciones();
</script>

I leave a link to the jQuery documentation and the ajax method. link

    
answered by 09.11.2018 в 21:16