AJAX - Response
In the previous lesson we learned how to send an HTTP request using AJAX. Now let's learn how to work with the response.
function get_question() {
var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "https://opentdb.com/api.php?amount=1");
xhttp.send();
}
get_question();
The console will show a JSON, which is a string representation of a Javascript object:
{
"response_code":0,
"results":[
{
"category":"Entertainment: Books",
"type":"multiple",
"difficulty":"easy",
"question":"Who was the author of the 1954 novel, "Lord of the Flies"?",
"correct_answer":"William Golding",
"incorrect_answers":["Stephen King","F. Scott Fitzgerald","Hunter Fox"]
}
]
}
Now let's create a function to convert the JSON response into a Javascript object so we can work with the response.
As the request will take some time to return we need to use a callback function to make sure we won't try to do the conversion before the response is received.
function show_question(data) {
var questionObj = JSON.parse(data);
console.log('The question is: ' + questionObj.results[0].question)
}
function get_question(callback) {
var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
}
};
xhttp.open("GET", "https://opentdb.com/api.php?amount=1");
xhttp.send();
}
get_question(show_question);