Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
Ajax saving array into global variables not working keep getting undefined

Trying to save an array retrieved from ajax into a global variable such that I may use it later on but keep getting undefined error

   <script>
    var items = [];

    function add(value){
        items.push(value);
    }

    $(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'xxxx.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            for(i=0; i < result.length; i++){
                add(result[i]);
            }
        },
    });
    });

    document.write(items[1])

    </script>
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

This is an asynchronous AJAX call. The call to add will be done at a later time than the execution of document.write(items[1]);

So this is the right way to do it:

<script>
    var items = [];

    function add(value){
        items.push(value);
    }

$(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'xxxx.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            for(i=0; i < result.length; i++){
                add(result[i]);
            }
            document.write(items[1])
        },
    });
});
</script>

This way the function that uses the result, will be executed when the result function is executed.

Think it this way: you said: Here is this lemon basket. Then you asked someone to go somewhere and get the lemons and before he returned you tried to count the lemons. Got it ?

about 4 years ago · Santiago Trujillo Denunciar

0

You can use ajaxstop to call the method after the ajax request has completed. Place the following function in document ready:

 $(document).ajaxStop(function () {
     document.write(items[1]);      
 });

The above solution works but this is another option I used when waiting for multiple ajax functions to complete. This will call every time you complete an ajax request but there is a way to limit to one call if need be.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda