Push an array into an array in javascript (jQuery)

I am trying to get the push () method in a loop to build the structure as follows:

var locations2 = [ ['User', position.coords.latitude, position.coords.longitude, 1], ['Bondi Beach', -33.890542, 151.274856, 2], ['Coogee Beach', -33.923036, 151.259052, 3], ['Cronulla Beach', -34.028249, 151.157507, 4], ['Manly Beach', -33.80010128657071, 151.28747820854187, 5], ['Maroubra Beach', -33.950198, 151.259302, 6] ]; 

This is my code:

 var locations = []; $.ajax({ type: "POST", url: "/ajax/map.php", data: "name=test", dataType: "json", cache: false, success: function(data){ $.each(data.points, function(i,item){ array_push = ["test", parseFloat(item.origem_lat), parseFloat(item.origem_lng), i]; locations.push(array_push); }); } }); 

However, the Javascript console.log for locations shows an empty array.

I try to use push () in different ways, but I cannot get the same structure as location2. The biggest problem here is that I don’t know how many arrays will be inside the array of locations before the loop, so I cannot initialize it in advance.

Any thoughts?

+7
source share
1 answer

I realized what the problem is. This has nothing to do with the push () method itself. Apparently, ajax calls are not executed in sequential order (which is the reason the asynchronous). I added async: false in the ajax call options, and now everything works fine.

Thank you all for entering.

+4
source

All Articles