I am trying call an ajax request until it returns a true value. I have tried the following code but it does not return any results and no errors in the console. Any idea what I am doing wrong?
function getUserData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
return resp.status;
}
}
xhr.send();
}
setInterval(function () {
if (getUserData() === "true") {
alert("true");
}
}, 10000);
getUserDatacalls an asynchronous function internally, so it has returned long before the AJAX call is actually finished.Instead of doing this in a setInterval loop, you might want to try calling
getUserDataagain in the failure case. For example: