Please enable JavaScript.
Coggle requires JavaScript to display documents.
AJAX Annotation 2021-03-25 082350 - Introduction - Coggle Diagram
AJAX
- Introduction
below shows how AJAX works.
An event occurs in the client (the user types something in the search box)
The browser sends an HTTP request to the server with the search term
The server looks for data that matches that search term in the database.
The server send the results back to the client. (Normally in JSON)
The answer is received and parsed to become a Javascript object.
The page content is changed to show the search results.
AJAX - Request
var xhttp = new XMLHttpRequest(;
State Description
0 Request initialized
1 Connection to the server established
2 Request received
3 Processing request
4 Response received and request finalized
200 OK - Response received successfully
403 Not authorized
404 Not found
EX
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
console.log(this.readyState);
}
xhttp.open("GET","
https://opentdb.com/api.php?amount=1
");
xhttp.send();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var responsObject = JSON.parse(this.responseText);
var question = responsObject.results[0].question;
var answers = responsObject.results[0].incorrect_answers;
answers.push(responsObject.results[0].correct_answer);
console.log('The question is: ', question);
console.log('The answers are: ', answers);
}
}
xhttp.open("GET","
https://opentdb.com/api.php?amount=1
");
xhttp.send();
AJAX - jQuery
$.ajax({
url:"
https://opentdb.com/api.php?amount=1
",
type: "GET",
dataType: "JSON",
success: function(data){
presen_question(data);
},
error: function(){
console.log("error");
}
}).done(function(data){
presen_question(data)
}).fail(function(){
console.log("error");
});
function presen_question(data){
var question = data.results[0].question;
var answers = data.results[0].incorrect_answers;
answers.push(data.results[0].correct_answer);
console.log('The question is: ', question);
console.log('The answers are: ', answers);
}