๐Ÿ”ฅ AJAX Course ๐Ÿ”ฅ

  • ๐Ÿ“ท link to the video course
  • ๐Ÿ”ฅ link to the practice app
  • ๐Ÿ’ป GitHub repository
  • ๐Ÿ‘จโ€๐Ÿซ created by Pava
  1. ๐Ÿ‘‹ Introduction

  2. ๐Ÿ“ž Async #1: callbacks

  3. ๐Ÿ‘ฝ XHR's: the dark arts of AJAX

  4. ๐Ÿคณ Async #2: promises

  5. ๐Ÿ˜Ž fetch: the modern hero

  6. ๐Ÿ’ญ Closing thoughts

  7. โž• BONUS

Agenda

App Setup

  1. ๐Ÿ’  INSTALL NODE & NPM

  2. ๐ŸŽ“ install git

  3. ๐Ÿ‘ช clone the repo

  4. ๐Ÿ’ป run "npm install"

  5. ๐Ÿ’ป run "NPM START"

  6. ๐Ÿƒโ€โ™‚๏ธ navigate to "localhost:4000"

  7. ๐ŸšŒ MOVE to the start branch

Getty Images Setup

1) Fundamentals

DEMO: A world with & without AJAX

[...] web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. - MDN

Asynchronous JavaScript and XML

jokes service
Browser
images
service
AJAX requests

Practice App Architecture

github 
static server
static files

The Collaborative Web

HTTP Protocol

DEMO: AJAX requests in action

ย 1) HTTP methods

2) http status codes

GET
POST
PUT
DELETE
...

ย 3) header

ย & body*

Asynchronousย  = !Synchronous

2) Async #1
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
for (let i = 0; i < 10; i++ ) {
    console.log(`Iteration number ${i}`);
}

console.log('Chuck Norris is a badass');







console.log('Wait, what?');
setTimeout(function textBob() {
    console.log('On my way!');
}, 2000); 
1.
2.
3.
4.
5.
6.
7.
8.
document
    .getElementById('logo')
    .addEventListener('click', textBob);

function textBob() {
    console.log("On my way!");
}
A callback is a function invoked from another function which received it as a parameter.
setTimeout(textBob, 500);


document
    .getElementById("logo")
    .addEventEventListener("click", textBob);
callback
callback

callbacks exercises

  1. ๐Ÿ“„ open the callbacks-exercises.js file
  2. ๐Ÿ’ป there are 6 sections in the file separating the 6 exercises & test methods
  3. ๐Ÿ€ good luck!
  4. ๐Ÿ”ฅ we'll do the first one together

callbacks Solutions

๐Ÿ”จ MOcky.io

๐Ÿ’ป Write the code

XML HTTP REQUEST

3) XHR
let myBody = {"temperature": 22};

let mockReq= new XMLHttpRequest();

mockReq.open(
    'POST', 
    'https://www.mocky.io/v2/5ad48e2f2e00005200583b9a'
);
mockReq.setRequestHeader('ajax-fundamentals', 'iampava');

mockReq.addEventListener('load', function onXhrLoad() {
    console.log(mockReq.response);
});
mockReq.addEventListener('error', function onXhrError() {
    alert('Oups, it seems something went wrong ๐Ÿ˜ž!');

});

mockReq.send(JSON.stringify(myBody));
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

Handling errors...

๐Ÿ˜† I know! We check the response status

๐Ÿ’ป to the code

The load event fires when we have an answer from the server while the error event when we've got an error on the Network Level.

Debugging...

๐Ÿ“ญ POSTMAN

ย ๐Ÿ‘จโ€๐Ÿ’ป dev tools

vs

PUtting the jokes together

Getty Images

  1. ๐Ÿ“„ consult the getty images api docs
    • โš  we need a paginated search by a certain phrase (chuck norris)
  2. ๐Ÿ’ป add a getImages function to our API module which gets a page of images
  3. ๐ŸŽจ call that function when the app starts and display the images on the screen

images Solutions

CORS: ๐Ÿ˜‡ or ๐Ÿ‘ฟ ?

Cross-Origin Resource Sharing (CORS) is a mechanism  [...] to let a user agent [...] access selected resources from a server on a different origin (domain) than the site currently in use. 

A user agent makes a cross-origin HTTP request when it requests a resource from a different domain, protocol, or port than the one from which the current document originated. - MDN

CORS in action

๐ŸŽ Wrap up #1

๐Ÿ”ฅ Promises ๐Ÿ”ฅ

food example
A Promise is an object representing the eventual completion or failure of an asynchronous operation. - MDN
4) Async #2
let goodPromise = Promise.resolve("hello");
goodPromise.then(
    (resp) => console.log(resp)
);
let badPromise = Promise.reject("nay");
badPromise.then(
    (resp) => {},
    (err) => console.error(err)
);
let after5Seconds= new Promise((resolve, reject) => {
   setTimeout(() => {
        resolve(Date.now());
    }, 5000);
});

after5Seconds.then(
    resp => console.log(`The time is ${resp}`),
    err  => console.error(err)
);

Promises exercises

  1. ๐Ÿ“„ open the promises-exercises.js file
  2. ๐Ÿ’ป there are 6 sections in the file separating the 6 exercises & test methods
  3. ๐Ÿ€ good luck!
  4. ๐Ÿ”ฅ we'll do the first one together

promises Solutions

๐Ÿค” So...callbacks or Promises โ‰

  • Short answer: Promises
    
  • Long answer: let's find out ๐Ÿ”ฅ
You've just found this dog.ceo API and decided to build an online catalogue that shows the name  + a photo for each of the breeds.

When you look in the documentation though, you realize that they don't have a way of returning both the picture & the name of the breed race.

So you must make 2 calls, one to get all the breeds and then another one to get the pictures of each breed.

๐Ÿค” Possible solution

getBreeds(function onBreeds(breeds) {
    for(let i = 0; i < breeds.length; i++ ) {
        getBreedPhoto(breeds[i], function onBreedPhoto(photoUrl) {
            document.body.innerHTML + = `<div> 
                <img src="${photoURL}" />
                <p> ${breeds[i]} </p>            
            </div>`;
        }, failureCallback);
    }
}, failureCallback);

๐Ÿค” what if we have more calls to make?
ajaxCall1( function onSuccess1(resp1) {
    
    ajaxCall2(resp1,  function onSuccess2(resp2) {
        
        ajaxCall3(resp2, function onSuccess3(resp3) {
            
            ajaxCall4(resp3, function onSuccess4(resp4){
                /*...*/
            
            }, failureCallback);
        
        }, failureCallback);
    
    }, failureCallback);

}, failureCallback);
๐Ÿ‘ฟ Callback Hell ๐Ÿ‘ฟ
ajaxCall1()
    .then( resp1 => {
        return ajaxCall2(resp1);
    })
    .then( resp2 => {
        return ajaxCall3(resp2);
    })
    .then( resp3 => {
        return ajaxCall4(resp3);
    })
    .catch(failureCallback);
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

ย 

ย 

typeof fetch === 'function'
5) Fetch

Sending AJAX requests with fetch

๐Ÿ”จ MOcky.io

๐Ÿ“ญ POSTMAN

๐Ÿ’ป Write the code

let myBody = { temperature: 22 };
let mockReq= new Request(
    'https://www.mocky.io/v2/5ad48e2f2e00005200583b9a', 
    {
        method: 'POST',
        body: JSON.stringify(myBody)
    }
);

fetch(mockReq)
    .then(resp => {
        return resp.json();
    })
    .then(jsonResp => {
        console.log(jsonResp);
    })
    .catch(
        err => alert('Oups, it seems something\'s wrong ๐Ÿ˜ž!')
    );
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

Handling errors...

๐Ÿ˜† check the response status #2

๐Ÿ’ป to the code

The fetch promise will resolve if any answer
comes back from the server.

ย 

This means that even if the promise fulfills, we might have an error status code (eg: 404, 500)

jokes #2: fetch

Getty Images: fetch

  1. ๐Ÿ“„ consult the getty images api docs
    • โš  we need a paginated search by a certain phrase (chuck norris)
  2. ๐Ÿ’ป add a getImages function to our API module which gets a page of images
  3. ๐ŸŽจ call that function when the app starts and display the images on the screen

images Solutions: fetch

6) Deploying the app

๐Ÿ’ญ CLOSING THOUGHTS

7) Bonus

References

App Setup | References

Introduction | References

Callbacks & XHR| References

Promises & Fetch| References

Bonus| References

made with โ™ฅ by Alexandru Pavaloi
https://iampava.com

thank you! ๐Ÿ™

AJAX Fundamentals | online course

By Pava

AJAX Fundamentals | online course

Slides for my free AJAX Fundamentals video course. You can find it online here: https://iampava.com/courses/ajax-fundamentals/

  • 231
Loading comments...

More from Pava