Reputation: 1
I code jquery like this
var machineId = [];
$.getJSON('ajax/getmachines.php', { plant: vPlant, floor: vBuilding + vFloor }, function(dataList) {
$.each(dataList, function(recordno, machine) {
machineId.push(machine['id']);
alert(machine['id']);
});
});
alert(machineId[0]);
The first alert in the $.each
shows the right data every record but why the last alert show me undefined? How can I use array machineId
? Thanks.
Upvotes: 0
Views: 181
Reputation: 66398
The getJSON
method is asynchronous - when the run time engine reach the last alert, it didn't finish to execute yet.
You can't use the array before the callback has finished.
Just do whatever you need to do from within the callback, for example:
$.each(dataList, function(recordno, machine) {
machineId.push(machine['id']);
alert(machine['id']);
});
alert(machineId.join(", "));
This will show all the ID's separated with comma.
Upvotes: 0
Reputation: 6726
The request is asynchronous so the last alert is executed before the array is filled. Try to place the "alert(machineId[0])" after the $.each operation.
Upvotes: 2