run one or more callback functions when the data is resolved or rejected
REMARKS
As soon as you receive data from e.g. an API (resolved state), you can process this data in the default callback function of the AJAX methode or in one or more done() or then() methodes
Any errors (rejected state) can be intercepted with both catch() or fail()
.always() is a very handy methode to hide e.g. a preloader because this methode runs both after a resolved state or after a rejected state
The .then() method accepts a resolved and a rejected callback and is equivalent to using done/fail together, such that:
$.ajax().then(resolveCb, rejectCb);
// is equivalent to
$.ajax().then(resolveCb, rejectCb);
We are only interested in the key data witch contains an array of six users
<divclass="border-gray row"id="users"></div>
1
$.getJSON() is by far the simplest and therefore the most recommended method of retrieving JSON data
Line 8: In this version, we use the default callback function to get all the users and add them to the page
Line 25: the cache() methode is only triggered when the API sends an error or when the URL is not accessible
(Change const url temporary to a non-existing URL to trigger the catch() methode)
Line 28: the .always() methode runs always
const url ='https://reqres.in/api/users';const pars ={
page:2,};// version 1: $.getJson() with default callback function
$.getJSON(url, pars,function(users){
console.log('users', users);let cards ='';// users.data[] contains 6 users
users.data.forEach((user)=>{
cards +=`
<div class="card">
<img src="${user.avatar}" class="section media">
<div class="section">
<p>${user.first_name}${user.last_name}<br>
<a href="mailto:${user.email}">${user.email}</a>
</p>
</div>
</div>`;});$('#users').html(cards);}).catch(function(error){
console.log(error);}).always(function(){// this function is always run last});
Line 2: remove the default callback function and move the logic to a separate done() methode line 3
// version 2: $.getJson() without default callback function, but with then()
$.getJSON(url, pars).done(function(users){
console.log('users', users);let cards ='';// users.data[] contains 6 users
users.data.forEach((user)=>{
cards +=`
<div class="card">
<img src="${user.avatar}" class="section media">
<div class="section">
<p>${user.first_name}${user.last_name}<br>
<a href="mailto:${user.email}">${user.email}</a>
</p>
</div>
</div>`;});$('#users').html(cards);}).catch(function(error){
console.error('API not resolved!', error);}).always(function(){// this function is always run last
console.log('Request completed with success or error callback arguments');});
Line 2: replace the done() methode with the then() methode
line 3: the first function inside done() is the resolve function
line 20: the second function inside done() is the reject function and (can) replace the catch() methode
// version 3: $.getJson() without default callback function, but with then()
$.getJSON(url, pars).then(function(users){
console.log('users', users);let cards ='';// users.data[] contains 6 users
users.data.forEach((user)=>{
cards +=`
<div class="card">
<img src="${user.avatar}" class="section media">
<div class="section">
<p>${user.first_name}${user.last_name}<br>
<a href="mailto:${user.email}">${user.email}</a>
</p>
</div>
</div>`;});$('#users').html(cards);},function(error){
console.error('API not resolved!', error);}).always(function(){// this function is always run last
console.log('Request completed with success or error callback arguments');});
$.getJSON(url, pars).done().catch().always()
is now:
$.get(url, pars, 'json').done().catch().always()
IMPORTANT: it is not recommended omitting the last parameter(json) of the .get() methode
jQuery tries to 'guess' the returned data type, but this often goes wrong...
// version 4: $.get()
$.get(url, pars,'json').done(function(users){
console.log('users', users);let cards ='';// users.data[] contains 6 users
users.data.forEach((user)=>{
cards +=`
<div class="card">
<img src="${user.avatar}" class="section media">
<div class="section">
<p>${user.first_name}${user.last_name}<br>
<a href="mailto:${user.email}">${user.email}</a>
</p>
</div>
</div>`;});$('#users').html(cards);}).catch(function(error){
console.error('API not resolved!', error);}).always(function(){// this function is always run last
console.log('Request completed with success or error callback arguments');});
// version 5: $.ajax()
$.ajax(url,{
url: url,
type :'GET',// you may delete this line because GET is the default value
data: pars,
dataType:'json',success(users){
console.log('users', users);let cards ='';// users.data[] contains 6 users
users.data.forEach((user)=>{
cards +=`
<div class="card">
<img src="${user.avatar}" class="section media">
<div class="section">
<p>${user.first_name}${user.last_name}<br>
<a href="mailto:${user.email}">${user.email}</a>
</p>
</div>
</div>`;});$('#users').html(cards);},error(error){
console.error('API not resolved!', error);},complete(){// this function is always run last
console.log('Request completed with success or error callback arguments');},});
The status code is available through the third parameter with the xhr.status property
Line 10 to line 12: show some feedback on the page if the status code is 204
const url ='https://reqres.in/api/users/7';
$.ajax(url,{
url: url,
type:'DELETE',success(response, textStatus, xhr){
console.log('response', response);
console.log('xhr', xhr);
console.log('xhr.status', xhr.status);if(xhr.status ===204){$('#user').text('User successfully deleted');}},error(error){
console.error('error', error);},complete(){// this function is always run last
console.log('Request completed with success or error callback arguments');},});
line 2: replace the value for apikey with your API key
As you can see in the form, the name attribute of the form elements matches exactly the keys for the query string we have to append to the fetch URL
This makes it super easy (only three lines of code) to serialize the form(opens new window) with JavaScript
The result of this serialization is a string like this: apikey=yourKey&t=Pulp+fiction&y=&plot=short
Line 54 to line 59: serialize the form and append it to the fetch URL
Result: fetchMovie('https://www.omdbapi.com/?apikey=yourKey&t=Pulp+fiction&y=&plot=short');
The rest of the code follows just the same logic as the code in the previous exercise
const omdbapi ='https://www.omdbapi.com/';$('form').submit(function(e){
e.preventDefault();
$.getJSON(omdbapi,$('form').serialize()).then((movie)=>{// info if movie not foundlet info =`
<div class="card warning full-width">
<p>No info found for <b>${title.value}</b></p>
</div>`;// overwrite info if the movie is foundif(movie.Response ==='True'){const poster = movie.Poster && movie.Poster.length >10?`<img src="${movie.Poster}">`:'';
info =`
<div class="row">
<div class="col-sm-6">${poster}</div>
<div class="col-sm-6">
<h2>${movie.Title}</h2>
<p><b>Genre: </b>${movie.Genre}<br>
<b>Released: </b>${movie.Released}<br>
<b>Actors: </b>${movie.Actors}<br>
<b>Director: </b>${movie.Director}<br></p>
<hr>
<p class="text-justify">${movie.Plot}</p>
</div>
</div>`;}
document.getElementById('movieContainer').innerHTML = info;}).catch((error)=>{
console.error('API not resolved!', error);}).always(()=>{$('.spinner').hide();});}).submit();