AJAX - jQuery
The jQuery library provides a method to do ajax requests in a simpler way. Let's do the example from the previous lesson but this time using jQuery.
$.ajax({
url : "https://opentdb.com/api.php?amount=1",
type: "GET",
dataType: "json",
success: function(data){
console.log(data);
},
error: function(){
console.log("Error in the request");
}
});
Note that when we pass the dataType as JSON, the response already comes as a Javascript object so the conversion is not necessary.
We also don't need to test the status of the reqsponse because the ajax method already has the built in success and error methods.
These properties are callback functions that will be executed after the response is received.
We can also define the success and fail functions using the done and fail methods.
$.ajax({
url : "https://opentdb.com/api.php?amount=1",
type: "GET",
dataType: "json"
}).done(function(data){
console.log(data);
}).fail(function(){
console.log("Error in the request");
});