0

Hello everyone this is my first question in stackoverflow, thanks for your help. I have an array to which I want to add more elements that I receive in json format from my database.

$more_products = [
    'any_one',
    'any_two',
    'any_three'
];

In my product table I only have 3 records and I add them to the array.

$.ajax({
    type : "get",
    url  : "{{ url('products') }}",
    success : function(data){
        for(i=0;i<data.length;i++){
            $more_products.push(data[i].name);
        }
    }
});

console.log($more_products);

When I show the array, length: 6 is correct, but (3) why?

output:
(3)["any_one", "any_two", "any_three"] 
0: "any_one"
1: "any_two"
2: "any_three"
3: "monitor"
4: "keyboard"
5: "mouse"
length: 6

If I show the array, it only shows me three elements, why?

for(n=0;n<$more_products.length;n++){
    console.log($more_products[n]);
}

output:
any_one
any_two
any_three

I expect to have 6 elements in the array, but those that I add from within the $ .Ajax do not save it, why?, someone has some idea of what happens, thanks

With two simple arrays and works without problems, here the code. https://jsfiddle.net/tqdmq2uo/8/

ErikROCHA
  • 1
  • 1
  • 2
    `$.ajax` calls are async, so your `console.log($more_products);` instruction are running before `$ajax` gets resolved – guijob Feb 27 '18 at 17:21
  • Both of the linked dupetargets ([here](https://stackoverflow.com/questions/14220321/) and [here](https://stackoverflow.com/questions/38660832/)) are at play here, combining to make things even more confusing than usual. TL;DR: You're logging the array before the ajax call completes and puts something in it, but he console shows you *live* information. The (3) you're seeing is how long the array was when you first logged it, but as of expanding it, you see all six entries it has at that time. – T.J. Crowder Feb 27 '18 at 17:22

0 Answers0