I've got the ajax request is very slow so my stats array does not get updated at the second time i want to access it. It seems like the ajax request gets executed after all the code is processed. Is there a way how i can wait for the ajax request to be executed before all the rest of my code?
console.log(stats);
fetchREST(false, (url selectedID "/solve"), (parseInt(button.id) 1), function(data){
if (data.success) {
console.log("richtig");
stats.right ;
} else {
console.log("falsch");
stats.wrong ;
}
});
console.log(stats);
function fetchREST(isGET, path, answer, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
let email = "*";
let pw = "*";
if(isGET) {
// not needed
} else {
let solutionArray = '[' answer ']';
console.log(solutionArray);
httpRequest.open('POST', path, true);
httpRequest.setRequestHeader("Content-Type", "application/json");
httpRequest.setRequestHeader("Access-Control-Allow-Origin", "*");
httpRequest.setRequestHeader("Access-Control-Allow-Headers", "*");
httpRequest.setRequestHeader("Authorization", "Basic " window.btoa(email ":" pw));
httpRequest.send(solutionArray);
}
}
EDIT I fixed it by changing
httpRequest.open('POST', path, true);
to
httpRequest.open('POST', path, false);
Now the async is set to false and the send methods waits until a response is received.
CodePudding user response:
I fixed it by myself by changing
httpRequest.open('POST', path, true);
to
httpRequest.open('POST', path, false);
Now the async is set to false and the send methods waits until a response is received.