I am currently developing a quiz application for the Noops Challenge on Github, utilizing the Fizzbot API available at Noops Challenge.
To keep track of the current question and the next question URLs, I have defined global variables to store and assemble them.
var baseurl = "https://api.noopschallenge.com";
var nextQuestion = "/fizzbot/questions/1";
var url = "";
There is a submit function in my app that sends a POST request to the server. If the answer is correct, it then retrieves the URL of the next question.
function submit() {
var answer = document.getElementById("answer").value;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
this.nextQuestion = response.nextQuestion;
this.url = baseurl + this.nextQuestion;
console.log("Next Question: " + this.url);
}
};
xhttp.open("POST", this.url, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(answer);
}
In addition to the submit button, there is also a next button in the quiz app. Even after answering correctly and submitting, clicking the next button still logs the same URL - .
function next() {
console.log(this.url);
}
The issue seems to be related to the asynchronous behavior of the POST request. I need to find the best solution to resolve this problem. For a more detailed example illustrating the situation, check out the complete snippet provided below.