*NEW* Speed Up Webpage Loading 2021 - Part 1: AJAX, XMLHttpRequest and the Fetch() API | Clyde Matthew | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

*NEW* Speed Up Webpage Loading 2021 - Part 1: AJAX, XMLHttpRequest and the Fetch() API

teacher avatar Clyde Matthew, !false | funny, because its true

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

18 Lessons (1h 35m)
    • 1. Course intro

    • 2. How browsers used to work

    • 3. Ajax

    • 4. Don't get lost in all the detail

    • 5. XMLHttpRequest Object

    • 6. Building the XMLHttpRequest Object

    • 7. Dealing with response data

    • 8. AJAX example - displaying time from a server

    • 9. Building our custom time function

    • 10. Picture and name example

    • 11. Defining our request listener function

    • 12. Summary of the XMLHttpRequest Object

    • 13. Fetch()

    • 14. Setting up our fetch

    • 15. Fetch using JSON

    • 16. Fetch with a POST request

    • 17. Fetch vs XHR

    • 18. Conclusion

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class



We will cover of ton of information about speeding up your webpage loading in this two-part series. In Part 1 we concentrate on how browsers request information from a server. 

I'm excited about this section, because it sets the foundation and base for the rest of the classes in this series. 

Why is this important to understand? 

The entire process of loading a page is known as the critical rendering path. Having an understanding of the critical rendering path will allow you, as a developer, to structure your website for optimal performance.

Before we get into the CRP in detail, I want to give you some useful background on how browsers used to request data from a server, and what we have available today (spoiler alert, we speak about both the XMLHttpRequest object and Fetch()). 

I can't wait. 

Lets get into it.  

What this entire series covers?

Why 1-second matters hugely?

A one-second delay in page load time yields:

  • 30% fewer page views
  • Less customer satisfaction
  • Loss in conversions

Aside from influencing ranking well with Google, a few extra seconds makes a big difference to viewer attention, interest, conversions and hence profit.

Understanding the Critical Rendering Path will enable you to become an awesome programmer. Take control through understanding. Delivering a fast web experience requires a lot of work by the browser. Most of this work is hidden from web developers: we write the markup, and a nice looking page comes out on the screen. But how exactly does the browser go from consuming our HTML, CSS, and JavaScript to rendered pixels on the screen? By understanding this, you will be able to write better code in order to boost your website traffic, know how to precision fix and tweak behaviour and performance, improve your market penetration and your margins. You’ll also gain an advantages over other developers who seem to just push the buttons without fully appreciating what is happening.

In this course you’ll learn about the Critical Rendering Path. This refers to the set of steps browsers must take to fetch and then convert HTML, CSS and JavaScript into living, breathing websites. From there, you’ll start exploring and experimenting with tools to measure performance. You’ll learn simple, yet very powerful strategies to deliver the first pixels to the screen as early as possible.

Knowledge of the CRP is incredibly useful for understanding how a site's performance can be improved. There are various stages to the CRP, such as constructing the DOM, constructing the CSSOM, running JavaScript, creating the Render Tree, generating the Layout and finally Painting pixels to the screen. As you can see, this Skillshare series covers a whole bunch of interesting material.

By the end of this Skillshare CRP Series, you'll be able to “speak” CRP by gaining an understanding of how to fetch data from a server and then get that data to your user as quickly as possible. We dig deeper in every lecture, learning about things like HTTP, TCP, data packets, render blocking resources, and a whole bunch more! This course has many bonus lectures which extend your knowledge base and test your skills.

Through practical examples, this course helps you understand the CRP piece by piece. And we use the latest and best features of JavaScript and browsers (like the new Fetch API) along the way so you can stay ahead of the pack.

Is this course for you?


It doesn't matter where you are in your web development journey. It's suitable for all levels.

Still unsure? If you fit in any of these categories then this course is perfect for you:

Student #1: You want to dabble in the world of programming: learning the fundamentals of HTTP, AJAX, Data Packets and Rendering will allow you to extend this knowledge to any language

Student #2: You want to gain a solid understanding of web performance

Student #3: You want to start using backend frameworks like Node.js, which are heavily dependent on having a deeper knowledge about how to make AJAX requests, manipulate the response and then deliver it to the screen

Student #4: You kinda know what the Critical Rendering Path is, but have little knowledge about how it works behind the scenes, and how to practically implement it in your code

Student #5: You have taken other courses in web development but just don’t feel like you’ve grasped it


Meet Your Teacher

Teacher Profile Image

Clyde Matthew

!false | funny, because its true


Ideas are a dime a dozen. The hard part is execution. Unfortunately, most people never carry tasks to completion.


I've worn many hats in my career …  As a result, I have an ability to view all sides of a coin, something that is becoming crucial in our tech-savvy world.  


My experience and a few words:


·        I’ve had to learn things the hard way (aka: hard slog)

·        I want to teach people what I’ve learnt, with the hope of making a meaningful impact (cliché, but true)

·        No one is a master of everything. But at the same time... See full profile

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Course intro: Skill, say students to yet another course. And this course is all about wig speed. That's right. How fast can we get your webpage displayed to the screen? How foster not talking about small silver fast, just like a greyhound. Let me show you. Here we go. Just like skinny the ground. Could Gil she's still a puppy By the way. Anyway, in order to deliver a very fast web experience, your browsers to do a lot of work behind the scenes. And I say behind the scenes because as developers we write our code and in the browser just displays the pixels. But how exactly does your browser convert our CSS, HTML, and JavaScript into something that's actually practical on either a tablet, phone or PC? Well, if you answer that question, you'll become an awesome programmer because you'll be able to, a write bit occurred BY, you'll be able to assess the performance of your website. See you be able to drive more traffic to a website and deal increased margins as a result until it's all about. And actually there's another benefit and that is you'll be a better programmer because most programmers just press buttons and see results without fully appreciating what's happening behind the scenes. But now before we go further, yes, I'm talking about websites speed. But the lingo, the jargon and the industry is that this whole process is referred to as the critical rendering path. And this critical rendering path don't get intimidated by it. All it is, it's the entire process. It's a process beginning from the browser sending an HTTP request to a server. The server then processing that request and sending it back a response to the browser. The browser then has to manipulate that response. It has to do something with that response. It has to form a render tree. It has to understand all the diffs, all the paragraphs or the headings. And then finally, the browser has to paint everything to a screen. Mission choices is called the critical rendering path. And that's what this entire course is all about. Medea students who've, and we get into a lot. We talk about HTTP to our talk about packets, TCP, server interaction. We talk about ajax. We look at the new API, the Fetch API. I even talk about how to audit your site so you can increase with performance. Because let's be honest, if your site doesn't load within a second, you're going to be losing visitors. So these are things you have to know. It's so, so important. Now, the way skill she works as I'm sure you know, is that they prefer us lecturers doing bite sized classes rather than one long course. And that's why you'll see that I've split up this entire course into different parts. So please follow me along started Part one and just continue sequentially. We're gonna have a lot of fun together, but yeah, I can't wait. This first clause we're going to be talking about browsers, how they work, and we're going to be looking at the Fetch API. We going to be looking at age x. It's going to be really cool. So without further ado, I'll see you now. 2. How browsers used to work: Old school, I know it's boring, but in order to understand why the wave has developed as it has, we do need to understand it. So what is the old-school way of how browser used to fetch data from server. Lowly probably can guess. Browser would have seen to request. It will then have to wait and then it would receive a response. And pay journey in this way was very intuitive. If nothing went wrong, any acids that made up the page would be downloaded and displayed on your computer or device. So let's see how this looks. So your browser with seemed an HTTP request to your server that within weight, your server would then process that request and it would then send an HTTP response to your browser. This was the way that websites worked for many years. But this had a number of floors and the biggest floor by far is and that's why it's number one. Page reloads. What I mean by this. Well, think about it whenever you wanted to update any part of your website. For example, to display a new set of products. Or if a user wanted to update his profile, his name, or age, the entire page at Dillard again. And this practice is very resource heavy and results in poor user experience, especially as your websites become larger and larger and more complex. Ok, Clyde, that's grades are not the problem, but what is the solution? Well, I don't want to give you a spoiler alert. So you're going to have to wait until the next lecture to find out. 3. Ajax: Enough of the old school way. How is this problem resolved? And the answer is drum roll. And the problem of having to reload pages every time new content was page from a server. The way that their problem was solved was by technologies allowing webpages to request smaller chunks of data like HTML, XML, or JSON, or even just plain text. And allowing these browsers today in only display that text or that resource or that data when needed. And how do we achieve this? What kind of technologies can we use? Well, we can use many APIs, such as XML HTTP requests. This is the heart of Ajax. This is way at age x or began. We've got new ones such as the Speech API. And these techniques are known as using ajax. And can you guess what ajax stands for? I'll give you a clue. That tried. It stands for Asynchronous JavaScript and XML. And as I just mentioned, originally, it mainly used the XML HTTP request object to request XML data. Hence the word in ajax, the X stands for XML. But these days don't stress about XML because you're more likely to use the same object, the XML HTTP request object, the Fetch API, both of those, we're going to be using them to fit JSON, not XML, XML's old school, but the result is still the same, whether we Fitch agents, HTML, JSON, or even plain text. And this is why the term Ajax has stuck around. But if you're anything like me, you probably want to see this visually. But let me try. Let me do my best. Yeah, you've got your browser and your server, just like we had before. And in the middle we've got this technology called Ajax. And how does this help us? Well, your browser now scenes request, but it doesn't seem that to the server directly at scenes it via Ajax. Ajax then scenes and HTTP request in the background. Let's drop, does its business. And it seems an HTTP response. And in Ajax provides the daughter to the browser. But what is so awesome is that whole process of the HTTP request and the response. You guessed it. It happens in the background without us having to wait for page reloads. How awesome set. But wait, there's more to speed things up even further. Websites today also store acids and daughter on your own computer's hard drive on your computers database. And how does this work? Well, very simplistically and a high level, what happens is when you request a web site for the very first time, a lot of those assets that are fetched from the server will be stored on your computer in a database. Meaning that next time you visit that same site, on subsequent visits, you are able to use local versions of the data instead of downloading Frisch copies all the time. And that also means that content is only reloaded from the server when that dot on the server has been updated. Palaces look, will your browser can now request data from a database. Your computer will then ask, does daughter need to be updated? His daughter been updated on the server? And it isn't. A simple solution is they can just send that daughter straight back to your browser. This results in a very fast load paging time. This is awesome. This is why mini sites you visit. It's almost instantaneous. Okay, but now say that the daughter does need to be updated. What's going to happen name? Well, the first check your computer has to do is wall, are you online or not? Let's say another line will in that case, unfortunately, the daughter basis is gonna send you the daughter has any still going to be looking at outdated data. Cool. I think we've got that under wraps. What about now if your computer is online? Databases, Gunnar CGD request to Ajax, to this technology piece sitting in the middle. Ajax will then send an HTTP request to the server. The server will do its business that's going to send an HTTP response when it's ready. Ajax will store the data in the database, but now it's updated data and net to be sent back to your browser. And the screen looks a bit funky, right noun is lower on a per hope you gaining an understanding of how this all works at a very high level. At least we're gonna get into more detail shortly there. So bear with me. 4. Don't get lost in all the detail: Sometimes you can stand so close to the wall. You can see the painting. And I don't want you to get lost in all the detail. Just think to me simplistically what happens. Think about it like this. You go onto your mobile device, raise mine. And we go, you go on to know more about the lies and began to Safari it onto Google, whatever phone you using and you go and visit a webpage. The dots has to come from somewhere. Bright conscious display data to your screen without fetching it from somewhere. And that's why you have a server you normally load or your daughter files or your resources, your assets to images onto the central server. That server then delivers all this content to your phone, to my phone, to browsers, to a PC. And that's what we're discussing here. And we've seen the old school way with that process could take a while NIMART time, you wanted to update a little section of your site, the whole page and to read OK. And that's just excruciating, especially in the world that we now live in. So what's happened? Well, like us in new technologies have come into the picture. We have ajax now and I could leave it there. We could just stop bats and wanted to show you what ajax actually is. And I want to look at both the original ajax, the XML HTTP request object, and also new APIs that have come on to help us even improve food, such as the Fetch API. So before we move to the other sections, understanding how the request and response works, I do once you and I together to look at ajax, lets quickly now look at the XML HTTP request object. And let's make some requests to assess and finite. 5. XMLHttpRequest Object: I've driven the point home and a wool one Morton, the keystone of Ajax is the XML HTTP request object. The XML HTTP request object exchanges dots with a server behind the scenes. And all this means is that it's now possible to update parts of a webpage without reloading the entire page. Okay, well that's very cool, Clyde. But how do we actually access this object? And where does it come from? And does my browser just might advise actually have this? And the quick answer is yes, all modern browsers, Chrome, Firefox, IE seven plus 0J Safari, Opera, eccentric, cetera. They all have bolt in XML, HTTP request object right out of the box. Well, I've just mentioned that the XML HTTP request object is available on all browsers. Well, let me prove that to you. So I've just opened up Google Chrome is just access the console. And now I just want to access the Window object. And don't stress if you don't know what the window object is, highly encourage you right now to go and complete my JavaScript grandmaster cause this in the, we talk in detail about the Window object and what it is. But for now, let's just concern a lot the window object. Let's open it up and let's look for the XML HTTP object for we're going to be near the bottom automation. And there we go. There is the XML HTTP request object straight out of the box in our browser. I haven't done any coding. This wasn't as we have this right out of the box. Okay. Now that that's out of the way, let's move on. I've mentioned this as well before, but despite its name, XML, HTTP requests don't only deal with XML data. This object can be used to retrieve any type of daughter. What kind of daughter will XML, JSON, HTML takes images, et cetera. Okay, great, so we've seen that XML HTTP request is the main Ajax technology, but how do we use it? Will have broken it down into three simple steps. Step number one, we have to seek up our request. In other words, we have to access that object. The second step is to create a fraction that runs when the request is done when you receive that response. Because making a request to a service, one thing. But in dealing with their daughter when it comes back is the crux of programming. And that's what's step two does. Handling bolding these functions, we have a few properties that are available to us straight out of the box from this object. And one is a status and a 3D state. Property. Status codes are just data help us understand whether our question response was successful. So anything in the 200 range is a good thing and are considered as exists. So that's a status code. And then we also have the 3D state. And the 3D state properties. Actually quite cool because it defines the current state. That is why the word status in their 3D state. It defines the current state of the XML HTTP request object. And this property has an event handler for an event that fires at every state change when the ready state is 0, that means the request has not even been initialized. And when it goes all the way up to four, we know that the request is finished and the responses ready. Very cool. And you can understand soon how these work. But we're not quite done because we've set up our quest. We've created a function that deals with the response, but we haven't yet done anything with that request headway. And that's we stick three comes into it, and that is we have to open and cmd our quest. H2, that is a lot is another Walden. I hope you're understanding how this all works. Now, this is a lot of theory and I don't like theory. I love practical examples. So why don't you and I jump over to a coding editor and let's make our very own ajax call. Just remember these three steps. So before you go into the next lecture, remember these three steps. One, we need to set up our UK waste, then we need to create a function. And lastly number three, we need to open ends in Iraq waste. So let's do that now. 6. Building the XMLHttpRequest Object: Let's now put together an example where we request data from a website called JSON placeholder, and you can just Google it, but Jason placeholders just a site that provides real API endpoints in scenes Beck placeholder content. So you can think of Jason paid-up plate, blueberry, blueberry blue. So you can think of JSON place holder is a site that just contains a whole lot of data that you and I can make requests to WIC data from. It's pretty cool. And you can see in front of us we have Visual Studio Code, open net rhyme using, but let me just be clear at this point, we don't have to use Visual Studio code. This is just one of a plethora of text editors out they infect even to make Ajax calls, we can even use the browser directly, but I just love Visual Studio code. It's awesome, it's free. So that's what I'm going to be using here. Okay, so we've got Visual Studio Code open. Let's start creating some files to fetch data from JSON place holder. So obviously asking me for a folder which I have indeed create delicious Craig or Norma desktop. Let's create a folder called ajax tastes. Then as folder, let's create an index.html file. And let's reference a JavaScript file called app.js. This can be anything. So of course, we have to create a file, JavaScript file called app.js. And this is our JavaScript file. This is where all the magic is going to happen and where we're going to start writing our code. And let's begin. Let's build our XML HTTP request object, coal. And you remember how to do this? What was the first day I tried step one was to sit up our request. And how do we do that? Well, we can call our object anything. Let's just call it XHR because that is industry norm. And here we're going to access the XML HTTP request object. And we've already seen that this is available to us right out of the box. Why do we have that new keyword? Well, if you've done my course, my JavaScript complete grandmaster course, you would know, but that new keyword day is used to instantiate a new object via constructor function so that XML HTTP request function allows us to use the new keyword. Basically just creating a new object, our own object that we can start manipulating and using. That has all the properties and methods available to us from the XML HTTP request object. Cool, let's keep going. So though we have this XHR object, we haven't yet done anything with it heavily. And we can prove that if we console log r XHR object. And remember how we said that it has a 3D state property and status. Will let see what this is. Let me just remove this side. And I'm sorry, I keep showing us healthy at the bottom right of the screen because I have extra things to say. Now, the few ways you can stay this within a browser, I used live server. So if you go to extinctions here within Visual Studio code, you can download a hall of plugins. The ones that I'm gonna be using right now is called live server. You can search for a chair. This is the one yet the purple looking one. Something else that is very useful that I'm gonna be using in this course is also another plugin called Crocker caucus brilliant and allows us to actually run JavaScript right within Visual Studio code. But I'll be showing you that a bit later. So as I mentioned, we're using live Goliath, the live server. We can click on that. And here we go. It's opened up the file that we've created. If we inspect us, we can see here, it's just, it's just clear everything in our reload. You can see here are 3D state property is 0. That's awesome. Remember what the ready state means? The 3D state gives us the state of the XML HTTP request, and they are only five states. 0 means, you guessed it, nothing's happened. One is when the connection is established and Server. Two is when the server receives the request. Three years when the server is busy doing its thing and it's busy manipulating, fitting all the data. And fall is when it's done and the responses ready. So let's head back to our console. Hey guys, we've done step one, step two. Well, remember we said stiff T2 was creating a function to deal with the response when it's done. And how do we do this? Well, remember we logged ready state to the screen and it was Xero books, nothing was done. And what does the final number? Plus four? That means that everything is complete. What we didn't console log, which we can do a piano just for completeness sake, was the XHR status code. And the most important status code for us is 200, because 200 means success. You'll be well familiar with the 404 error. We don't like that. We want success. We went to a 100. Okay, so let's continue. We want to create a function now that deals with the response. But how do we know at what point this function needs to run? Well, the traditional ways to access our objects, our request object. And there's a property called on ready state change. And what unready state change does is it's kind of like intervened handling. Every time the 3D state property changes, it will fire the function that we defined here. So that's what that means. Let's define our own function. And we only want this function to run on a successful process, on a successful request and response. Her. Let's just use a typical if if statements. We wanna say if our objects ready state is four, because that is when it's already done and dusted. And we want our status to be 200 thing. We want to execute our code. In our case, let's just document, right, all down to the screen. And then for completeness, just to show you this console log the ready state and status. Now at this point in time, nothing's gonna happen. Why? Because we haven't implemented state three. We haven't actually seen this requested server. Let's do that now. Or we need to do is finish this off by step three and that is open, our open and seen our request. How do we do this? Will we access our object? We open our request. We are opening our connection to the server. The first argument is the method. And you can see up text editors really giving us clues as to what arguments are acquired. We need our method and we need the URL. So let's define a get method here. And the second argument is the URL. The URL, yes, HTTPS. Jason, placeholder. So Pico.com, forward slash posts. So there we go. We've opened our quest and the last thing we need to do and seen that. Now let's see if this works. There we go. Who is net Awesome? So let me just show you that again. That's clear. Our console we're gonna do now is just refresh this page and they have it. This really state and the status initially when we console log that out with zeros each. But when the response was ready to be sent back to us, we've got a 3D state of four and a status code of 200. This is exactly what we would expect. How cool is that? We've just done your very first Ajax request, and now we've had a response, but all we've done now is reprinted the taste, all done on screen. We haven't really done anything with that response ever. So in the next lecture, let me show you how we do that. 7. Dealing with response data: Getting me, but there's still a way to go. So remember how we just wrote this code and we printed all done to the console. We've defined our function to be executed when the response daughter's been seemed to us baths, you'll notice that we haven't dealt with any response data heavy. Now. So let's do that now. First thing I want to show you is what does this response data look like? Well, if we console log at this point in time, our XHR object, what would you expect to see? See what it looks like? Let's go back to our browser. So let's clear the console so there's no confusion. Refreshed the page. The first two zeros you see Day is the ready state and the status. If I go back to the editor, it's the very two consoles at the top. So this is before we've even seen the request, which is why they 0. But if we go back to our browser and we console log our response, this is what it looks like. If we open it up, this is what it looks like. Now, what we are interested in is this response text. This is We, the daughter from, in our case, jason place all the edge weights all put into. So we want to access the response takes property. How do we do that? Let's go back to our text editor and Stewart. It's deleted console and needs go lead daughter, for lack of a better word, we can call this anything we want. And that response text property that we just saw, we want to convert it into a JavaScript object because we want to manipulate it and we want to use JavaScript to do so. So the way we do that is we access the JSON object and we access the past method within it. And you can see my text editors are really telling us that this converts JavaScript Object Notation or JSON string, which is what that response text is into a JavaScript object. And we could write x h r response text like this. But there's a better way and that is to use the, this keyword. So we can do that because this does refer to the XHR object itself. And we want to access that response takes, don't we? And in our case, let's just say we want to access the first item with Internet. And just for completeness, let's console log data to see what it looks like. It's got our console. It's clear everything in this refresh. And here we go. We've exist The very first user. And we only access the first user. Because this response takes returns an array and object. And we want to access the first element in that array, which is the first user. And what about if we wanted to now console log all their daughter to our website, to our page. Well, we can do that. Let's write to the screen thought to think this will work. Let's have a look. Hasn't worked as it, it's displayed to us. Object, object, because this is still a JavaScript object, we haven't yet converted it back to plain taste. And in order to do that, we have to again exits that JSON object and is a method on this called stringify. And we want to stringify data if we now visit our browser, pods, your Android. Okay, so now we've managed to get data from JSON Plato place holder, which is actually just a server somewhere out day that has well they taught and we've literally made a call via Ajax. And we've literally pulled it back and display the touchscreen. How cool is this? I hope he signed to feel more intuitive about this. I hope assigned to make scenes. And there's one thing you might be wondering though. Remember in our code here we did exist this JSON.parse and JSON dot stringify. We've actually sees methods but where they're from. And again, most browsers, if not all browsers now have this JSON object available to us. And I can prove that to you if we just go back to our console. And again, let's console log the Window object and just look for the JSON object. And there it is. Yeah, it's the JSON object. And you can see we've got parse and stringify, which are methods available to us directly out of the box, we have the writers, which is why in our code we were able to access JSON.parse and JSON dot stringify. Crew hookah. Take a step back. Just remember what we've done. Step one, we set up our quest and we've just chosen this instance to use the XML HTTP request object. We set up our request to a server, stick to within decided to create a function that deals with that response once it comes back to us because we have to do something with it. In our case, we just document wrote to the screen, we just displayed to the screen the very first US head was returned to us. And if we just did step one and step two, we would have all our code ready. That you guessed it. We wouldn't have actually seen the request to the server. That's why we need step three. Step three is kind of like just finishing it off. It's just sending that request. Think about an envelope in the post-its, you literally putting it later into the postbox. So step three, we open and send our request. And this is all good. This is all awesome. We've just done a lot, but I want to do more examples with you because the upcoming lectures and sections get lot more complicated. And I want you to feel very, very at ease with this concept. I'll see you in the next lecture. 8. AJAX example - displaying time from a server: When it comes to coding, there are many ways to do exactly the same thing. We've really discovered that yourself. So I want us to explore the XML, HTTP or waste a little bit more detail in a little bit differently to what we've done previously, because that's the awesome thing about programming. We can do things in many ways. There are many ways to skin a cat, as they say, Well, what do I want to go through in this LinkedIn will let me show you this example on my screen right now. I'm wanting to have a hitting and net the hitting at the very end. I want us to have the time, but I want that time to be dynamics. If I go and reload this page, are there time to keep updating the ego? If I keep updating, it should update the recipient. How would I do this by making an Ajax call? All is one way to learn that is, let's call it together. Let's do it. Let's do this via XML, HTTP request object. So let's go to our code editor. Let's get rid of decks. That's what I'll quickly just drew up. And let's create a new folder. Let's call that folder XML HTTP request. Within this folder, the starting point is to create our index.html file. It's created basic template. In our body. We went to hitting domain and we want that to be tasting a Jx by using XML. And let's see what this looks like. Nebraska. Let's close this other one down. And then we go, we've just got all simple hitting that we've just created. We then went to reference JavaScript file. Let's just call it app.js. We can call it anything we want. Then of course we've got it creates an app.js file. Okay, now let's get into the nitty-gritty aspect of creating our XML HTTP request object. But this is fun. I remember how we created the previous XML HTTP request object. We did it in three steps, and the first step was to set up our request object. We called it XHR. The second step was to create a function that deals with the response. And the third was to open and seemed that request. And I want to do something slightly different yet. So I want us to kinda muddle the sticks around a little bit. And I want to create our own function that deals with the error handling in the callback of the response. Let me show you what I mean. So I should say, the first step is to create our very own function. And we can call our function anything we went and For now we haven't defined it. So it is going to throw an error. But let's just define our very own function, get data. And the very own function that we create is going to accept two arguments. The first argument is going to be the URL, and the second argument is going to be a callback function that's gonna get either an era where the actual data itself and An execute function when that is received. Well, the first thing we wanna do is deal with an era if we get one. So we can say if Iran does not equal to null, then list just console log flips. And let's console on the IRA. Else if we've got no errors, this is where we can handle the meat of what we wanna do and what do we want to do? Well, we wanna get the top, remember, and we want that to be dynamics. Everytime we reload, we went another feature to happen and we want the new time to be displayed. How can we do this? I'm going to be using third party website called adjacent kleeks ninja would look like. So we can open up a browser here and we can talk to Jason tastes.com. And yeah, we got json.dumps. You can see at the top it utilizes JSON and it allows us to make requests to it and Fitch, Jason and manipulated to test our code. It offers various services. The one that we are interested in is the date and time service. And let's just say we want to get the time. So how do we get this time? Well, you can see here that the end point has to be the header dot JSON taste.com. So let's do that. First day. Let's define our URL here is HTTP time because that's what we want to get, JSON tastes.com. So there we go. There's our URL. When we are successful, let's define a variable called text. We can call it whatever we want. And we're going to use template literal CIA. If you don't know what these are, please see the complete JavaScript grandmaster calls. And we're gonna say, we're gonna access the data. And that daughter's going to be passed into our callback function, provided there is no era. And we're going to exist the time property of that object. Lastly, we want to access our headings are H1 tag in HTML. So XIST elements by tag name, we want to access one tag and if we just lifted it, this just bear in mind the get elements by tag name. That method returns a collection of all elements in the DOM with the specified Tag name, in our case H1, but it returns it as a node list. And because we only have one H1 tag, we only want to access the first element of this entire node list. So we have to exist first item within netlist, which will give us our H1 tag. And they enlist just pinned the ticks that we've just written a to that H1 ED. Okay. We've done quite a bit, but at this point in time we haven't even defined the gate daughter function. This will not work. If we access our browser and we try and refresh. The console is not defined. We know that because we haven't yet defined what it is. We've just calling the function here out of suny. So let us define a function. 9. Building our custom time function: So let us define a function. I know what I want, I'll functions do, but we haven't yet written it. So let's do it is to find a function called gate daughter. We've already said that this takes two arguments rise. The first argument is what? Great, that's the URL. The second argument is the callback. And now we can start defining this function. And now we've gotta go through the motion again. Step one of creating an XML HTTP request as what? That's right. It is creating an instance of the XML HTTP request object. So all we have to do here is we have to define a new object same as exactly the same as we did last time. And you should be very familiar with us now, the next thing I want to do at this point is I want to open the request. I want to open the request and the connection with the server. So now let's open the request. We exist the open method. Remember the first argument is good with exactly the same previously, we went to visit the URL that we pass into the function. In this case, it's gonna be timed JSON tastes and we want it to be asynchronous, which is why we pass true, which is optional. We don't have to do this. Another optional thing we can do is we can exit the response time. The response type a Finds What type of response we expect so we can exit the response type. And we want that to be Jason. Now, remember in the previous example, we used the unready state change event handler to actually define what happens when evidenced success that was actually stayed. To remember stick to we, we defined our function. What to do with that response from the server? Well, that unrealistic change is a bit cumbersome and is a bit away. And it only came out later. So I wanted to show you the old school way, but it is a better way called onload. So this User tab, this access, our object, let us say it is listed says, yeah, let's just say let's use the load method. Unload was on, load was added later, whereas on ready state change has been around since Paul fell off the bus. So let's do that. We access our exec are our XML HTTP request object exist on load method. And we want to fire function when this happens. And I'm going to be using the new arrow syntax. And what do we want to happen? Well, let's just define a variable called status in. Let's say that's our status. We already know this and hopefully the status at this point is 200. So we say if the status is 200, then that's far our callback function. There is going to be no aeronautical Beck. And if I scroll down here and remember, our callback function has two arguments, that's era and daughter. He had is going to be no hair. Why? Because we said if the status is 200 thin executors. So if that is the case, our error is going to be null and the data that comes back is going to be in this response property. And unfortunately, sometimes the art, there is an era which means if the status isn't 200, what do we want to happen will again, we wanna call the callback. But in this case, we want to pass in the status crew. So they we have at HOCl is us. We are almost done. Right now. We haven't done step three heavy. So this is kind of if, if, if we just scroll up here, step one was creating the XML HTTP request object. This is kinda stick to because we've created the function. We've created what we want to happen when the response is returned to us. And now we need to do step three. And it is seen that the request we x is our variable and we seen that get rid of these extra lines. And there you go. Literary than another entire example around the XML HTTP object. Let's see if it works out. That see if it works. Let's go to our browser. The refresheverything, uncaught syntax error, unexpected token. We have, we're going to unexpected token. Of course, you can see here. Yes, I'm using arrow syntax and I forgot to include the error. Let's see now if this works. And then we have at how awesomes us. Let me just get rid of the console. And there you go. There's a time and we refreshed and we read Walden. But there's one more example I want to show you as well that see that next. 10. Picture and name example: I know you probably going to be chasing me with a pitchfork bat. I want to do one more example with XML HTTP request. I want to show you something else and bear in mind the fact that I'm doing things differently is a good thing because it means as a developer, you can kind of fit in your group, your own groove. And if you like certain ways to do something, do it. There is no prescribed. The correct way to do some mini cases in programming is just what you prefer it as a goal. Let's look at one more example. What is the example? Well, I want to create similar to what we did last time, a hitting, but now I want to pull an image from a server and then I want to display the user's name below. And every time I refresh. You can see this is a brand new image in a brand new name. And I want to use ajax and when you use XML HTTP request to do this. So let's get started. Let's create a new folder. Let's just call it XML. Xml. And within here, and this creates our index.html file. And also let's create our app.js file. Let's start with our index file. First it is. Let's start with a template HTML5 setup. Immediate zoom in here a little bit. And what are we gonna do? Well, firstly, that's ever hitting, we can call it tasting XML HTTP request. Again. And this creates an unordered list for our image. And let's have an id of USA. And of course the last thing we need to do is reference our JavaScript file. You go. So there we have it. If we go and display index file now on site, we just have our hitting tasting XML HTTP request again, and nothing happens. We don't get, get the image or the user's name yet. So let's go back down coding platform and let's start working on app.js file will start working on this. The first thing I wanna do is I want to set up our entire request. And in this case, I want to use a website called random user. Just bear in mind, I'm giving you all these different sites and places to call daughter from for your benefit. Just so you know that there's a whole plethora of sites out there where we can test out code and work with daughters. So awesome goals. I'm going to be using random user. Let's go sit up our request. First thing I wanna do is I wanted to find our URL. In this case, our URL is HTTPS, random user.com, forward slash API, that's our URL. The next thing I want to define as I'll method. In this case, we're just getting daughter. We not posting dotted deleting or updating daughter. We just retrieving data and displaying it to the webpage. And let's work through the emotions. First, we have to create a new XML HTTP request object. And we do that with the new keyword, and we access that object out of the box. And just to show you the steps that we're gonna be going through on a console log. I want to console log this entire request. I want to see what it looks like. So let's just say here. This is what our request looks like initially. And I wanted to look that up to the console. Makes thing I wanna do is I want to open a connection. So this x is our object. And let's open the connection. We need to posit a method which we've defined as method. We need to pass it the URL and we want it to be asynchronous. They regard, Can you see how much quicker with Typing Now, can you see how intuitive this is becoming an hub at this point, Jana, standing what it is we doing at every step? What do we have to now? Yes, there's one thing we haven't done and that is define the function we want to execute when we've received the daughter. So let's do that in the user. It's been retrieved from the server. Let's do something and we will use onload. And we did this previous lecture, but we're going to use it again and just remain that that onload is executed when the request completes completes successfully. So I went to exist the onload method available to us straight out of the box. And when this event gets fired, I want to run a function. And we're going to define this. We haven't done this yet, but I just want to call it request handler. We're gonna get into defining that function shortly. I just want to set everything up now, sorry, instead of calling it request handler, let me call it request listener. And now I want to also handle, now, let's handle our ears. So it's good to handle areas. People always think about coding for the success case, but oftentimes when there's an error and you haven't handled it in a certain way, you don't know what the error is. Set what we're gonna do now. And just like we have the onload method available to us on the XML HTTP request object. We also have another method called on era. So the XHR on era is available to us. And here let's just call the function called request era, which will again will define shortly. And what is the last thing we have to do at tract? We have to send this request because if we don't seem that nothing's going to happen. So let's send the request. So XHR seemed cooler, so we've set everything up. Intuitively, it makes sense. Let me just run through it with you again one more time. We've defined a URL, we've defined a method. The URL is way we want to retrieve the data from in order to actually get the data from the server, we have to then create this new XML HTTP request object. We have to sit up eight ajax. In other words, that while we've defined this object called XHR, we've just done a console for our benefit. The next step is we have to open up a connection with the server. We do that with the open method available to us on this object. We pass in the method in the URL. Next, we want to say what happens when we get dead daughter. We do that by calling a function called group waste listener. We haven't yet written this function, so we're gonna do that next. We then handle eras. We've got code for the equity in the right. And then lastly, we seen the requested server all done and dusted. So now let's define our functions, our request listener function. 11. Defining our request listener function: So let's now write our function called request listener. And before we go further, I just want to console log. Again what the request looks like at this point. This is what the request now looks like. And I'm going to use the, this keyword. If you don't understand how this works, please do my JavaScript grandmaster cause a greatly does go into a lot of detail about the, this keyword that In summary, this function is being called. If I scroll down here, it's being called by the XHR object. Therefore, that will be the, this. In this instance. Remember how we previously saw that the response takes the stored in a variable called response text. Remember that? So let's convert the response takes into JSON. And we did that by using the JSON object Linked Data equal JSON pass. We want to access our variable, our HTTP request object. We want to access the request, the response takes variable, and we want to convert that to Jason, which is what we've done here. And just to show you what it looks like, we can say the response text is now converted to JSON and we can console log Datta will. Before we go further, let me just show you what we've done so far. The table lock. Just close these other tabs. Let's be the console. We have to define a quest area before we can go further. So let me just quickly go here. We need a function called request era. Then we can console log. Okay, so there we go. Let's refresh. Lucius, clear the console and refresh. Then you understand what it is we're doing. This first console, this is what our quest looks like initially, you can see there that we are console logging the object, the XML HTTP request object and the 3D status 0 makes sense. And if we go back to our code and we scroll down literary this console, every hair, it's right at the beginning. That's what we wanted to console. When we get down and we actually receive the response. We've done another console. This is exactly what's happened yet. Looks at kind of the same. But now the 3D status for are you with me? If we open it up, we'll have response text will have the data populated. And you can see this is the response takes it takes and we've want to now convert debt to JSON, which was why going back to the code, we've converted that data to JSON with the JSON parse method. And then to console log, we see this response takes is now converted to JSON. What does this look like? Well, that's literally comparing this response takes up the that you see to now. Thus, Let's open it up and you can see we've got an array. And within the array you've got, you've got a property here called results. And if you open up the results, these are user Simple as that. How awesome is that this try and access our user. So user equals data results and we wanting the first item in the result. And remember why we used results. If I go back to the screen here, let me just minimize this. And minimize this. Here's what it looks like. And there's a property called results. I haven't made up that word and that is provided to us from the API, from the website so that you do have to know about and you have to read whichever website you're requesting data from off it's your own server. You'll know exactly what you've called it yourself. Here we've called it results. When we open up that results, we wanting to access the first item in that array, which is the user. And that's exactly what we've done here. So now we've actually extracted that user from the daughter. How cool is this? To show you what that looks like. We can say console log, the user now looks like user. We go back here, let's just clear the console, refresh. He has a law consoles, but the last one, the user now looks like this. And they either, how awesome is this? But the email, sulfur number agenda, everything is there. And it's a JavaScript objects so we can manipulate it and extract data from it. So let's do that. Let's extract the data we want to use. The dots we would like to use and display on our page. Well, let's say we want the firstname. How do we access the first name of this user? Well, we gotta go in here and we're going to open up this user object. And they've called first name, first under the name property, which is an object. And they it's under the name first. So we went to excess. I'll use object. We want to access the name. Remember the name property, which is, which is again an object. And they, they call it first. We want to do the same with the last name. But yeah, they call it lost. This is check the coolant last. Yes, they do. And what about the image? Well, let's get the source of the image and reset kinda peak will looking here, we've got the picture object and within a we've got large or medium. This is used large. So we xis are use object again. We access picture and we want large. You have it. This is the data we want to display on the screen. But at this point in time, if we go back to our HTML page, you can see here we don't have. Places to put oldest daughter into. So let's create that, but let's do it. Not the easy way in HTML understood via JavaScript. So now let's create our HTML elements. Let's say the list, removing, create an unordered list in our index file, you know, HTML file. Now let's create a list item. And we just do that simple JavaScript for milliwatt document running create elements a lot. And we wanna do the same with an image, and we want to do the same with the paragraph. So we're gonna do image. And we wanna do paragraph. And with the image and image needs a source attribute. So it's xy SAR image, we've just created the source. We want to be source, sorry, let me actually change this to a SRC, Esau C. And that will now display the image, but we also want to display the user's name below to this excess are paragraph and access the inner HTML attribute of that. And again, misuse template literals. And we want to put the user's first name and the last name. Cool, that's great. We've done all of this, but now we haven't placed these tags anyway to the student. Now, let's paint these items to our HTML. How do we wanna do that? Well, if we look at our index HTML file, we've got this unordered list element with an ID of USA. So effectively we wanna put everything within net unordered list. So here what we wanna do is we want to, we want to get deaths ID, get element by ID user and we want to append list that we've created our ally. And then within netlist, we want to append the image. And then below that, we want to append the paragraph. They we go for. Let's just see if it works before we talked through it. Mission Completed, wholesome and sad, and keep refreshing. And they we go. Now you can see that it'll dot days annoying. So all we need to do to get rid of that dot, obviously, I don't want to be doing CSAs. This isn't a course on CSAs, but for completeness sake and to show you kind of how you would possibly dirt's terrible to put styles in your actual hitter. Yeah. But I just want us to be quick and dirty. I wanna style the UL elements. And I want to, I want to get rid of that paragraph, that little bullet point. So there just needs to go in the style of night. And if we go back to our page, the simple, simple, simple can remove this now. And we've done it. We've literally done it. And I just heard defining this fun and exciting just as much as I am because you have done a lot. And the whole point of this exercise is just to understand that there are many ways to do the same thing. And that the Ajax request object, in this case the XML HTTP request object. It's not scary. You know, it's very intuitive. And for many years this is exactly how it was done for a very long time. I'm gonna be talking about the feature API in the upcoming lectures. And it's very similar to this. It just helps us do it a lot more quickly. But for now, let's just recap what we've done. 12. Summary of the XMLHttpRequest Object: The first thing we did was we set up our entire request. We define the URL, we defined the method, we set up our XML HTTP request object. And remember this is straight out of the box united and have to type this or call an external library that is built into your phone, bolt into a laptop, built into your PC. Automatically. Okay. We created that object within, established a connection with the server. When the server comes back with a successful response, we use the onload event, which is also just given to a straight out of the box. And that would automatically, via this request listener function that we've defined. If this any era that's going to fire the request era function that we defined in. Lastly, we send that request to the server. You can always do these scenes on an info button is clicked off, something happens. But in our case, we've seen that when the page loads Koolhaas, so that is the request. We then have to now define this request listener because we have to tell our browser what to do when it receives the response. And that is what this whole function is about. The first thing we do is we get the data and we turn it into a JSON object and we change it into adjacent objects so we can manipulate it and use the data and display to screen. It just makes it easy for us to work with. We then get the user from the results property and we want to access the first item in that array. We then define first name, last name, and the source of the image. We then create the HTML elements we appended to our existing HTML unordered list tag. And then Bob's, your uncle, is all done and dusted. So I hope this is making scenes, if not, posts and questions in Q and a, I'm happy to help you. But now let's see the bid away and the more streamlined way of doing very similar things with the Fetch API. 13. Fetch(): You all know the same necessity is the mother of all inventions. And that's exactly what's fueled the development of the Fetch API. The worldwide web consortium, or W, WC for short, came up with specs, the working draft for the XML HTTP request object. And initially this object was used to retrieve, as the name suggests, XML. And it did this via HTTP from a server. And we've seen this in practice. We've actually done three examples of using the XML HTTP request object that does the job. But the problem is, is that it's rather complicated. And this is exactly why Fitch was introduced features the new native JavaScript API and it's supported by all browsers. Today. Let me show you just as with the XML HTTP object we said and we proved that it was natively available to us. I want to show you that with the fetch as well. So yeah, we've just got Chrome is just look at the console. And it's just console out the window object. Let's open it up. Nega days Fitch, available to us straight out of the box. Cool. So we know that features available on the window object automatically straight out of the box. And according to the Google Developers documentation, the Fetch API just makes it easy for you and I to make asynchronous requests and handle responses. It's easier than using the older XML HTTP request object. I know that there are other HTTP approaches, such as using observable with our XJs and how they focus on memory management, leak in terms of subscribe or unsubscribe and so forth and so on. And maybe they will become the new standard way of doing HTTP requests. Who knows? But now I'm just wanting to use by far the most popular and that is the Fetch API. Okay, but enough, what is stage and how does it work? Well, the phage function takes one man and tree argument and that is the URL. And one of the major differences between fh and XML HTTP request is the fact that fh uses Promises. And if you don't know what a promise is, again, just look at the grandmaster course on JavaScript. That's at a very high level, that promise will return either a success or a failure. If the promise returns a success, the vein function will receive the response object. If a failure is returned, the MCAT function will receive the error object. This is so simple and makes sense. This is awesome thing about Fitch. If we had to write out phage, what would it look like? Well, we've got the phage function. We then have remembered a promise. And that promise can either return a success, in which case the theme function is executed. All the promise can return an era, in which case the catch block of code will be executed. And that is that the phage takes one mandatory argument, the URL. When the theme statement is executed, you will have the response object as your daughter. And if the catches executed, you'll have the air object Azure data. Let's see how fh works in practice. 14. Setting up our fetch: Let's now get into the Fetch API. What example can we use? Well, let's say a user has a login and they've got a To Do list. A whole lot of things that they need to get done with a tags and completed or not completed. We just want to display the latest to-do list on the screen. Let's just assume that's what we want. And in order to do this, I'm going to use a website and other one called JSON place holder. And that again is just a whole list of daughter that you and I can just access and taste opcode with. Let's get into it. You see how we are in Visual Studio code. This is our editor, and let's not using the feature API. Firstly, we need to define the URL. So let URL HTTP is, and we sit is going to be Jason placeholder, right? Mostly for your side. This would be your server. And we wanting to access to-dos. So there you go. These are Euro. Next, let's define our Fitch. Remember in the previous lecture we showed how a Fichte Looks like. We use the phage keyword, which is available to us natively. And it takes one argument. One argument is the URL. And let's just provide for the case with the promise returns as successful response and in which case we'll have access to the response data. So we want to execute the theme statement. We want to take that data. And let's just say we want a console log their daughter to the screen. Let's execute this. X is the console. We refresh, and there we go. D is our response. It's open our response object. And look, what we get is not exactly what we wanted wasn't. 15. Fetch using JSON: What's going on here? We've used the Vin execution statement, but the information as you just saw was not what we require. Remember, we need the to-do list, so we need the todo item and we need with it's been completed or not. So the response object that is returned via their promise has a lot of information that we don't reply. So how do we get the information we need? We'll need to get to the body of the response. And luckily for us, we get adjacent method returned to us when we use the Fetch API. And adjacent method returns another promise. Again, remember what happens with the promise. We have to follow it with another Dane statement. And let's see how this works. When we receive the data the first time that response object we've already seen that returns to match non-relevant Information to us. So let's use that Jason method when we get the data. What do we want to happen? We want to take that data and we want to apply the JSON method to it. Then we need another Dane statement because remember that JSON method returns another promise. Then we want to take the whole of the new daughter and less console log the newdata. Let's see what this looks like. So she's guy here, clear the console and refresh. Unexpected token. Whatever they're not. May not mean to in the statement. And n0 we have it. That is our list of to-dos. How close S. So if we open this object tab, you can see we've got arrays with a whole lot of to-dos, the reader. So just bear in mind when you are using a for each statement you may have supplied at JSON method in order to get the information you're looking for, which we require two things. Type it. Let's look at another example. 16. Fetch with a POST request: Up until this point, we've been dealing with data requests. And although it probably is enough, we understand upcoming lectures and sections. Are we on the topic? I just want us to get a little bit more advanced. So this is a very quick lecture on a post request. I'm going to be using JSON place holder producer for we actually begin the media show you Jason place. Okay. So the first step is I want to show you what Jason placeholder is. Let's just type Jason placeholder here. And you can see we've been honest website before. If you scroll down, what's cool? Yes, they've got different resources. They've got different kind of endpoints that we can access. And one of the ones that we going to use now just file purposes is posts. So let's say we've got a user and we've got a site where people can post comments. This is what we're gonna do. We're going to access the posts URI. And this is the roots here. So we need to access it by using forward slash posts and were allowed to see examples. You'll see a quick example here. He has get a results we don't wanna do that. We want to push the resource, or in other words, we want to create a resource. You can see here the Fetch API or embed takes one mandatory argument that URL will. The second argument is optional. And name we can specify methods, the headers, the body, things like that, which we're going to do shortly. But bear in mind, this isn't a real post. We're not actually going to be changing the server on the other side. And that's what the seizure, the resource will not really be created on the server is just fake. And you'll see that the output that is returned astronomy server isn't theory the fake post that we've just created. Okay, how Harper's making seen so far. Let's get to Visual Studio Code and start coding. Let's do this. Let me just get rid of myself because you probably sick of seeing my face. The first thing I wanna do is create our index file. And all we wanna do here is we want to reference our JavaScript file. This create JavaScript file. We got. Now the first thing I want us to do is to create a post. And when you start creating real websites, you're going to have to have a certain format of a post. If we go to adjacent placeholder, we can see here that the format of the request has to consist of a title and a body and a user ID. So we can do that, that's created our own post. This just call it custom post. It's an object we know that we've just seen that consist of a title. It consists of a body. And it consists of a user ID, which just says one for our example. And I just mentioned the Feed API takes one mandatory argument, the URL, but it also takes an optional second argument. And we're going to need to use this when we start doing things like posts. Yeah, I don't only want to put the post in nail, so I want to specify the header. So let's do that now. Let's define our custom headers also as an object. And let's just specify the content type as application for slash JSon. And we can specify the encoding type as UTF-8, which is the most popular. You might know this already, but in case you don't, Why do we have headers? Why do we need to specify the content type? The header of the HTTP request specifies to the server what kind of data should expect. What I mean by that? Well, if the server accepts multiple content, then it can use the header request content type to know how to interpret the body of the request. For example, if the server accepts both XML and JSON, then if you specify in your header request, if you specify the content type as application Ford's as JSON, the server then knows to interpret your response as Jason. Whereas if you had the content type is text forward slash XML, this would inform the server to expect XML in the body. And yes, you are, right, we don't always have to put the header information in there because they are default. But it's like, it's kinda like you don't have to make your Baidu. But it's probably a good practice just to make your bed in the morning like a cysteine code. So you can just do it just where you can have clean code. Put your request headers in. Okay, now that that's out the way, let us now actually post to commit lates, post a comment. So we're using the Fetch API. We know that the URL is Jason placeholder, k.com, and we know that the resource was Posts. Remember we select few minutes ago. And this is the first argument, the mandatory argument, but by default, this is a gate request. How do we specify post request will that is why we need to pass in an object as the second argument to the feature API. Let's define a method in here as post this time. The second thing I wanna do is I want to specify hitters, and I want to use our custom header. The next thing is, let's include our body. Now how do we do this? Because what do we put somebody do it, put a JavaScript object to the we put Jason will think about it, what it is we're doing when we posting this to server, what does the survey have? To remind you that CO2, JSON placeholder. And let's go to the main page here again. Scroll down to Resources and if I access this URL, what do you expect to see? Here we go. Yeah, all the posts, the sample posts. And you can see that this is in JSON format, which means we are not able to give the server that JavaScript object. We have to put it into JSON. So let's go back to our coding editor. So we've got our custom post as a JavaScript object. Let's now convert that to Jason. Do you remember how to do that? I hope zone we access the JSON object, which is available to us by the browser within xy submitted on it called stringify. And we went to stringify, our custom post. This now converts our JavaScript object into JSON, which is awesome, which is what the server requirements. And it's also what we told the server we're going to be sending it. And remember not custom header, we see that we are going to be sending JSON, but we are not quite done yet only because now a fh returns a promise and we haven't done anything with that promise to let us do that now, we have to define a name because it returns a promise. It's get the response. And for now I just want to console log that responds to the screen. I want you to see what it looks like. We remove this and let's Xs the console to see what the response looks like. Let's inspect the console. And it's just clear everything and refresh the page. And there you go. We have our spawns. Remember the Fetch API, it returns a response object. It doesn't return the actual data we need. It returns a response object. If we open this up and provides us many different things to Brian, provides us the type. In this case, it's caused because we're going to another server completely that gives us the status, the one that we want as this body. But the problem is, is that it's a readable stream and we have to use other methods to access it. But we're gonna get into the actual Keith for now. I just wanted to show you that we received a response. I just want to, I just want to talk again quickly about this JSON object because it can get quite confusing and you need to know what it is we're doing here. Remember that the Fitch API returns a promise. And what's returned by the promise is error response object. We've seen this handleResponse object isn't actually the dots we normally one from the server. It has a lot of extra dotted, has a lot of extra metadata. What kinda metadata doesn't have? Well, it's got things like date, time, URL, the status of the response, exedra, etcetera. The one that we're interested in and we've seen it, is the body contained within the body of that response. But the problem with that is that that body is a readable stream. In other words, this awesome API allows request to be sent in chunks. And what that means is that we have to wait until all the chunks have been received in order for it to be put together. And because of this, we can't access the body directly. We have to use methods in order to access the body. The good news is that we have a few of these methods available to us straight out of the box we've seen at one of these methods is that JSON method. And the JSON method returns adjacent past JavaScript object. That's what it returns, which is great for us. So we use this 99% of the time, but we also have other methods. We have that takes method and that returns the body as a string. We also have the blob method. The blob method returns that body as a blob object. And we also have the array buffer method, which returns the body as an array buffer object. The point I'm trying to make is we've got a lot of different ways to access their body daughter, the one that we love because we are typing in JavaScript at the moment. And we want to manipulate the Response Body to display certain things on the screen is the JSON object, sorry, is the JSON method, but this is by no means the only one available to us. Let's get back into it. Okay, let's head back coding editor. What we should do when we receive the response is we should use one of those methods to access the actual body. In this case, we're going to use the JSON method. But the JSON method now also returns a promise we have to wait for large chunks of data to be processed. And because of that, it returns a promise. We then get the response data from net promise. And now I want to console log the new response data. Let's see what that looks like. So let's clear the console. Let's refresh. And there we have it. How awesome says this is our coast that we've just posted to the server. It's an object. We know that because he used adjacent method. Exactly. It is the exact body. This is my story, blah, blah. It's got an ID, it's got a user ID and title. You did it up, cause a CSI. It's very intuitive when you start going through these processes and start dealing with responses and requests. This is fun, isn't it? I hope you having as much fun as I am. But there's a few more examples I wanna show you before we hit, ought to just be with me, bear with me, keep going. Grab a coffee, grabber, Coke, grabber juice, and emits. Let's get going across in the next lecture. 17. Fetch vs XHR: Now I want you to actually compare the same thing, but by using XML HTTP request versus phage. And remember how he displayed the image. We took an image from the server and the name and we displayed it to the screen using the XML HTTP request object. Remember, that looks something like this. And I want us to write exactly the same thing. But now one has to use the Fetch API. So let's get into it. Yezhov coding editor. And again, let's start by creating an index HTML file. And as usual, this reference JavaScript file, let's have an app of JS file. And before we get into our JavaScript, this just include a hitting tag. And we can call it tasting the phage API. Similarly to other example, that's Heaven unordered list tag here with the user. There we go. So at this point in time, everything is the same as our previous example. Let's now go to JavaScript file. Let's just make this larger. And let's get into a solid's define a URL. And it'll be the same as last time. Random user API. And now let's use our feet API. And I'm going to be going very quickly through this because now you should know exactly what to do. What's the first argument again? That's great. It's the URL. And what does phage return? Let's write a promise. So we have to catch it by using the thing makes it. The vein method is gonna return response. Let's just call it the first response or response one. We want to convert that response one to one enshrined to a JavaScript object. And we do that by taking net response and applying the JSON method to it. So before we go further, let's just console log this out. So this will be responds to console log, response to. Let's see what this looks like. There's our hitting. Let's access the console. Refresh our page. And day we go, we get an array with the results, narratives we do receive a JavaScript object makes seems right. And if we open this object app, we get info, we get results. What's important here is that the JSON method doesn't quiet return what we want, does it? Because we need the data inside this results object further, thus, we arpanet and there you go. These are user. So we need to get within their results. And we saw this even when using the XML HTTP object. So this should be very familiar to you. Let's go back to our coding editor. And let's start doing a bit more dose-response data. So let's just write this and we want to actually create a function where their response to is received. And we want to execute this entire function. Remember how we needed to access the results array? So let's say user equals corresponds to, we want to access the results property and we want to access the first item within it. And we did the same with the XML HTTP object. That's why I'm going quite quickly over this. And to prove that we've got the user, this just console of the US equity. Let's go back to our page here. Clear everything and refresh. And then you've got days our user with God, or you've got her. And now we just want to display this data to our actual screen. Don't win. So let's do that. Let's just say for each user, we get, let's display the user on the screen. And why don't we just go through the same process we did last time when we were using the XML HTTP object. Let's go. We need to define a list item and which we can just do this plain vanilla JavaScript create element alive. And we want to do the same. Don't refer image and a paragraph, IMG and paragraph. And of course this list here is going to be image, and that's creates a paragraph. Next. Let's add a source attributes so that we can actually see the picture. So we're going to access our newly-created element image. We're going to then add a source attribute to it. And what is that source attribute going to be? Well, if we go back to our browser and we open up this user, we can see that it's under Picture. And this large, medium and thumbnail, let's just access the source attribute for the large image. Pretty simple, right? Ok, let's go back to coding editor. That's excess USA, the picture property on that, and we can access the large property. Now we haven't added the person's name to the screen heavily. The student now add the person's name below image. We do that by accessing our newly-created paragraph element. We exist the inner HTML attribute of that element. And we just use templates, patrols, and display the FirstName. And you guessed it, it lastName. Up until this point we've created all out elements and tags, but we haven't yet added them to the DOM heavy. We've just created them in code. We haven't needed to touch them. So let's do that now quickie. Let's now add all the elements to the DOM. Remember on our HTML file Academy actually just show you we've got the unordered list tag. Within that, we're going to be placing our list item. And within the list item we're going to have an image and the paragraph, The name of the user. So if we want to look at what's in the UL tag, we've got the ally that we've created, the list item. And we just want to upend our image within it we've created. And we also name when our pain. Below that. I'll paragraph we've just created. But we haven't actually put the LI element anyway heavy. And that's why we need to access our HTML document. We need to get element by ID. And we called it user, which is the UL tag. And then we just want to paint the ally on to that to finish off the phage API, the fetch method, what do we need? Well, to keep your code clean, you need the catch statements to get any eras. And let's just take the era that's given back to us. If there is one. And let's just console log. Oops. There's an era. I know that's not very prescriptive, but this isn't the purpose of this exercise. And I hope this has worked. Let's go to our site. And there you go. Yeah. Every time we refresh this and you image is going to show is that horrible bullet point. So we can just go same as we did last time. And of course it's not good practice to produce styles in here. But for the argument sake, luscious do it. We wanna exist unordered list and we wanna say list-style of math. And then you go the bullet point that has been removed. Literally used the API to XML HTTP object to do the same thing. And I'm sure you can agree with me Museum the phage APIs to so much one should have so much more streamlined and easy. So without further ado, I think we are ready to move on. Well done. 18. Conclusion: I know this may have been a bit long-winded, but I hope you've had as much fun as I have in putting this together. And B, this is so important for you to understand because we are going to be getting into advanced detail now about the HTTP request, the protocols, what a packet is, how the browser renders things to a screen. And if you don't actually understand the basics of what it means, we're not talking about a request response, then it's gonna be really confusing to you and you're not gonna get much either cause deaths while we've done this. So I hope you really have had fun, and I hope you've learned a thing or two. So what have we done up until now will, since Internet Explorer five was released in 1998, can you believe it as like ages ago, we've had the option since then to make asynchronous network calls in the browser using the XML HTTP request object. And usually we define object is XHR. I hope you can see where it comes from. A just comes from the XML, the ancient HTTP and are in the request SY, convention is to name our objects x, h, r. And quite a few years after this, Gmail and other really popular websites and applications, they made heavy use of this XML HTTP request object. And they used it so often that they gave it a name called ajax. But working directly with the XML HTTP request is a pain. We've seen it. And it almost always is abstracted by some library like jQuery because you use a directly is just very cumbersome. And this is where JavaScript came up with. The Fetch API makes it much easier for us to make requests and handle responses. And why is this all so important? Why are we talking about Ajax law? We talking about pitching daughter from a servant, displaying it on a browser will hurt by now you've seen at making requests to the server and displaying that to the screen is crucial. We've seen how important it is to make correct waste and deal with the response. This process basically forms the backbone of every single page you and I visit a hand. I really feel that now you get it, now you're with me. So without further ado, let's take an advanced view of Holocene tire process really worked behind the scenes. I hope you enjoy it. Lets go.