📷 link to the video course
🔥 link to the practice app
💻 GitHub repository
👨🏫 created by Pava
Agenda
App Setup
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
jokes service
Browser
images service
AJAX requests
Practice App Architecture
github static server
static files
DEMO: AJAX requests in action
GET
POST
PUT
DELETE
...
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
📄 open the callbacks-exercises.js file
💻 there are 6 sections in the file separating the 6 exercises & test methods
🍀 good luck!
🔥 we'll do the first one together
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...
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...
📄 consult the getty images api docs
⚠ we need a paginated search by a certain phrase (chuck norris)
💻 add a getImages function to our API module which gets a page of images
🎨 call that function when the app starts and display the images on the screen
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
food example
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)
);
📄 open the promises-exercises.js file
💻 there are 6 sections in the file separating the 6 exercises & test methods
🍀 good luck!
🔥 we'll do the first one together
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.
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
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...
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)
📄 consult the getty images api docs
⚠ we need a paginated search by a certain phrase (chuck norris)
💻 add a getImages function to our API module which gets a page of images
🎨 call that function when the app starts and display the images on the screen
6) Deploying the app
7) Bonus
App Setup | References
🔗 AJAX Docs
🔗 Chuck Norris Jokes service
🔗 Getty Images service
🔗 Programmable Web [ collection of online services)
🔗 Todd Motto API's [ collection of public JSON API's ]
🔗 HTTP Protocol
🔗 HTTP Methods
🔗 HTTP Status Codes
Introduction | References
Callbacks & XHR| References
Promises & Fetch| References
🔗 GitHub Pages
🔗 ?
Bonus| References
made with ♥ by Alexandru Pavaloi https://iampava.com