0

I´m using jquery get function to retrieve data from the server (Laravel application). The data is bysically an array of objects. Simplified the .js code looks like this:

$(function(){
    var results = [];
    var getIt = function(){
        $.get('results', function(response){
            $.each(response, function(index, value){
                results.push(value);
            });
        });
    };
    getIt();
    console.log(results.length);
});

But the console logs 0, so the array is empty; What is wrong with it. The array should be available to later functions. Thanks for advice.

BillCode
  • 3
  • 4
  • `$.get()` is asynchronous; you're trying to eat a pizza before it's been delivered. See the question I marked as duplicate for more details. – Rory McCrossan Nov 30 '16 at 14:45
  • thank you all for your answers; i tried to search for it, but in a wrong direction; it sounds more clear now; thanks; – BillCode Dec 01 '16 at 12:16

2 Answers2

0

You're using the results array before it has been populated. You need to wait for your GET /results to return first. Assuming the rest of your code works, the following change will console.log the populated array:

$(function(){
    var results = [];
    var getIt = function(){
        $.get('results', function(response){
            $.each(response, function(index, value){
                results.push(value);
            });

            console.log(results.length);
        });
    };
    getIt();
});
Nick
  • 6,967
  • 2
  • 34
  • 56
0

Because $.get is asynchronous, the results variable is still empty when the code is called. To see what I mean, try this:

$(function(){
    var results = [];
    var getIt = function(){
        $.get('results', function(response){
            $.each(response, function(index, value){
                results.push(value);
            });

           getIt();
           console.log(results.length);
        });
    };


});`
Jay Kravetz
  • 233
  • 2
  • 10