Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda