I cannot print out the values of my Array.

Asked

Viewed 60 times

2

I am unable to print the values added to my Array in the Console. The Console response is empty as if it had not added the values to the Array. Below follows the code and the XML Document.

Code Block:

      $(document).ready(function(){
          var Gostei = []; // Array que vai armazenar as notas boas
         $.ajax({
                  url:'NotasPorMes.xml',
                  dataType: 'xml',
                  success: function(xml){
                        $(xml).find('list').each(function() {
                        $(this).find('NotasPorMes').each(function(){
                        // Adicionando os valores de Gostei para o Array
                        Gostei.push([$(this).find('Gostei').text()]);
                        });     
                   });   
                },
                   // Se nao consegui ler o arquivo xml, exibo mensagem de erro no console
                   error: function () {
                      console.log("Ocorreu um erro inesperado durante o processamento.");
                    }
       });
       console.log(Gostei); //Imprime o valor do Array
    }); 

XML:

<?xml version="1.0" encoding="iso-8859-1"?>
<list>
  <NotasPorMes>
    <Mes>1</Mes>
    <Gostei>9</Gostei>
    <NaoGostei>6</NaoGostei>
    <Total>7</Total>
  </NotasPorMes>
  <NotasPorMes>
    <Mes>8</Mes>
    <Gostei>6</Gostei>
    <NaoGostei>9</NaoGostei>
    <Total>7</Total>
  </NotasPorMes>
  <NotasPorMes>
    <Mes>6</Mes>
    <Gostei>4</Gostei>
    <NaoGostei>9</NaoGostei>
    <Total>8</Total>
  </NotasPorMes>
</list>

The value is only printed if I put the console.log(Gostei); within the bloco $(this).find('NotasPorMes').each( function(){...});, Since the purpose of the code is to traverse the xml add the values to the array and then return this array with its values for due processing outside the block $.ajax({...});.

I hope I’ve been clear, I count on your help, thank you.

  • change the array creation, take var. ex: "I like=[];"

2 answers

1


What is occurring is that your AJAX request is assíncrona, which means that when you request javascript will not "wait" for the request to be completed to run the next block of code.

You can make your request síncrona changing the property assyncfor false.

If you want to understand better, follow the documentation in English.

$.ajax({
    url:'NotasPorMes.xml',
    dataType: 'xml',
    async: false  
});
  • 1

    Thank you for the reply Pedro Camara Junior, is really the problem was in assync. Thank you!

1

This happens because the method $.ajax is asynchronous by default, ie it will run in parallel, and your console.log(Gostei); will be executed before he’s finished.

Alternatively you tell the $.ajax method that you don’t want it to be asynchronous passing by async: false in the options:

$(document).ready(function(){
          var Gostei = []; // Array que vai armazenar as notas boas
         $.ajax({
                  url:'NotasPorMes.xml',
                  dataType: 'xml',
                  async: false,
                  success: function(xml){
                        $(xml).find('list').each(function() {
                        $(this).find('NotasPorMes').each(function(){
                        // Adicionando os valores de Gostei para o Array
                        Gostei.push([$(this).find('Gostei').text()]);
                        }); 
                        console.log(Gostei); //Imprime o valor do Array    
                   });   
                },
                   // Se nao consegui ler o arquivo xml, exibo mensagem de erro no console
                   error: function () {
                      console.log("Ocorreu um erro inesperado durante o processamento.");
                    }
       });

    }); 

Or log into the success function:

$(document).ready(function(){
          var Gostei = []; // Array que vai armazenar as notas boas
         $.ajax({
                  url:'NotasPorMes.xml',
                  dataType: 'xml',
                  success: function(xml){
                        $(xml).find('list').each(function() {
                        $(this).find('NotasPorMes').each(function(){
                        // Adicionando os valores de Gostei para o Array
                        Gostei.push([$(this).find('Gostei').text()]);
                        }); 
                        console.log(Gostei); //Imprime o valor do Array    
                   });   
                },
                   // Se nao consegui ler o arquivo xml, exibo mensagem de erro no console
                   error: function () {
                      console.log("Ocorreu um erro inesperado durante o processamento.");
                    }
       });

    }); 
  • Thanks for the reply Fernando Mondo, is really I forgot this detail of ajax. I tested with false asynchrone is solved the problem. Thank you for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.