I am trying to use a for loop to get JSON data from my API. The issue I am having (i think) is that the for loop is not waiting for the first data transaction before moving onto the next one, because retrieving data from the server takes time. However, I thought that is how the on.load function works?
If I run each "machineID" separately as just "41" or "43", it works fine. It is when I try to itterate through the list where I get errors. Any help is appreciated!
var activeMachines = ["41", "43", "45"]
var dict = {};
getData();
console.log(dict);
function getData(){
for(i = 0; i < activeMachines.length; i++){
var machineID = activeMachines[i]
var getAPIData = new XMLHttpRequest();
var url = 'http://127.0.0.1:8000/processes/apidata/' +machineID + '/';
getAPIData.open('GET', url);
getAPIData.send();
getAPIData.onload = function(){
var APIData = JSON.parse(getAPIData.responseText);
dict['temp' + machineID] = APIData[0].tempData;
dict['humid' + machineID] = APIData[0].humidData;
timeValue = String((APIData[0].dateTime));
dict['time' + machineID] = new Date(timeValue);
}
}
}
This returns:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at XMLHttpRequest.getAPIData.onload (dashboardScript.js:26)
And the console.log(dict)
returns only dictionary values for activeMachines[2]
, which is strange?