Transcripts
1. Welcome to the class!: Hello, everybody and welcome to our introduction to Ajax. This is where we learn how to use Ajax to retrieve data dynamically from the Internet and put it into our web pages. During this class, you'll learn everything you need to know to start using Ajax, including how to use JSON data, how to access public APIs, which is where the data comes from, and of course, everything you need to know to make an Ajax request, which is sending the data, reading responses, handling errors, and keeping our users amused while they wait for our Ajax request to finish. During this class, of course, we're going to build a project. This is what we're going to build. This little web page here retrieves headlines from a news API, displays them on one side of the page and when our user clicks, then it displays animated GIFs interpreting the headline, which is the best way I can think of, of making sense of the world's headlines right now. So, who is this class for? Well, it's an introduction to Ajax, but really, it is an intermediate class, in that it seems that you already know some JavaScript and that you're comfortable working with HTML. Of course, if you have any questions or comments during the class, please let me know in the discussion area. I'll get back to you right away, otherwise, don't forget to hit the follow button and I'll look forward to seeing you inside the class.
2. Soooo, what is AJAX, anyway?: So, before we dive into using AJAX, we'll have a little talk about well, what does it mean? What is that A-J-A-X? What do we actually do with it, and what are the pros and cons of using it? So, first of all, let's take a look at what AJAX means. Well, the first A stands for Asynchronous which means that if we're going to do something asynchronously, we start out asynchronous job, whatever that may be then go off and do something else while the asynchronous job is doing its own thing, completing we hope. Once it's finished, it will let us know that it's done and we're back off from whatever work we were doing before and then go deal with the results of that. My usual analogy for that is making my breakfast. The first thing I do is boil some water and then I make the rest of my breakfast. I don't wait for the water that finish boiling for my hot cup of tea. Before I make the rest of my breakfast, I just start that kettle and then do everything else and that kettle is like an asynchronous operation. I hope that little analogy works for you. Moving right along, the J unsurprisingly stands forward JavaScript. So, we've got Asynchronous JavaScript and then we get another A which stands for plus, really it's an and. For some reason, the AJAX people decided that it must always be spelled out as Asynchronous Javascript Plus, that's really an And, X which stands for XML which is what everybody used back in the day when AJAX was first invented, but nobody uses XML really anymore in front-end AJAX communications. Everyone uses JSON, Javascript Object Notation. We will have a mini look at what JSON is a little later in the class just to make sure we are all up to speed on that, nothing too tricky, but this is the format of data that's used for exchanging information between a server and a web browser. Speaking of which, what does AJAX do? Well, note this, this is the usual arrangement we have. This is the known AJAX way of sending information between a browser and a server. This is the scenario, in which we don't want to use AJAX really. Let's imagine we have a sign up form for a new website and we send our data to the server hitting a sign up in the point and then the server sends back our whole new web page. So, everything in our browser changes and boom, we have a brand new page loaded in our browser. We have that sign up form in our history. So, if we press the back button, we go end up back on the sign up form. So, this is what we use AJAX for. Imagine we have a web page open and it's some kind of search tool, you can see you got a little magnifying glass in her browser and we send off our query. We hit some endpoint called Search on our server and we're passing a parameter that we want to search for, and then the service sends back some data, it doesn't send back a whole new web page. What we do is we take that data and jam it into the middle of our existing web page, we don't load a new one. So, clearly, that's quite a different experience for the user. You don't see the web page, so we get that and I see it reload. I just see the page that they were looking at originally with the new stuff suddenly appearing in the middle of it. So, what are the pros and cons of using AJAX? Well, on the happy side, this creates a great user experience when used well because it gives us very interactive and responsive web pages and overall, we are sending less data. We are just sending the data that we need from the server or we're fetching the data we need from the server through the browser and not a whole web page. One of the other things that we have to be a little bit careful of with AJAX, well, it can introduce complexity that would not otherwise be there in our web pages. I think that's a fair trade off because we're getting functionality that wouldn't otherwise be there as well. But the thing is that using AJAX can make the logic of how JavaScript code more complex. Using one two AJAX calls, it doesn't introduce too much trouble for us but when our AJAX call completes and has to make another AJAX call and that completes and that requires a third AJAX call, then it can be pretty tricky to know what's going on and if something's going wrong, debugging can be quite difficult. We have to be very careful finally not to break the back button because if we've got the results of some big AJAX requests sitting in a web page and user clicks the link, maybe that is in our AJAX data and then they click the back button, are they're going to see the results of the AJAX calls that we made previously? Well, unless we were careful to cache them and resend them, then probably not. They will be back where they started before this AJAX requests were made. So, you may be saying, well, what happened here? Users are used to the back button showing them exactly the same page that they left before they followed a link out of that page. So, now that we have had a quick look at what AJAX means, we've seen what it does and we've had a bit of a look at the pros and cons, we will start looking at how it's actually used in JavaScript in our next video lesson.
3. How to use AJAX in JavaScript: Okay. So, now it's time to talk about how we make a AJAX request in JavaScript. Today, we'll be looking at how we do that in JavaScript, obviously, using the XMLHttpRequest object, and how we can actually use it to make a request. So, XMLHttpRequest. So, what is that? Well, this is a standard part of JavaScript in a browser. So, it's always going to be available to you in a browser. It has everything we need for making an AJAX request in it. It's often, often, often abbreviated to just XHR or xhr in lower case because it is quite a mouthful. Finally, it's not to be confused with any number of other things that are used for asynchronous requests. There's a lot of stuff built on top of XMLHttpRequest and there are more things being built into JavaScript to handle asynchronous operations like promises, like Async/Await, and we're getting something called fetch soon. But XMLHttpRequest is the fundamental method we have for making an AJAX request. Just once again that XML in the name is totally misleading. We don't have to get XML back. Most of the time we'll be getting JSON and we'll be seeing a little example of that shortly. The first thing we need to do is to initialize and or create a new object using the new operator, and then we will call open on it. We are going to look at each of these things in detail in just a second. So, don't worry too much about this list that I'm rushing through right now, but the first thing we need to do is call open, which is to say how do we want to make our request and where are we going to make our request to? Then we want to assign a function to something called onload, and this is what we'll get called when the request completes successfully. We also want to assign a function to a property called onerror, which will be called if there's an error making the AJAX request. Finally, we can call send, which will actually send the request. So, let's take a look at that in code because that's quite a abstract, the list there, and it'll be much better to see it actually working. Okay. So, here I am in an example document. It's an HTML file with some JavaScript inside it in between script tags. I've done it this way just to make sure everything's in that one place and easy to see. I've included this in the resources section so you can go and take a look at it and play with it yourself if you want. But I'm just going down to the bottom of the document here and this is where our actual HTML is, right down here. I don't see where I will select it. There we go. This is one of our actual HTML body and the bits that we're really interested in are here. We've got a button when clicked will execute a JavaScript function called Load image. Then we have a little image with an ID of GIF and sources set to nothing. So, let's check out this Load Image function. Here it is. We can fit it on the screen, that's great. So, we define a function called Load Image, and here we are instantiating a brand new XMLHttpRequest. Let's skip over this for now, I'll come back to it very shortly. Then we call open on our brand new AJAX request and we say well we want to execute a GET method against a URL. Here is the definition of our URL. I've broken it up into bits just to outline each part of the URL. I normally wouldn't do it like this, so we're making a request against this endpoint here, which is part of the Giphy's API for returning a random GIF. Generally appending a question mark to say there's going to be some parameters on this URL. We're setting our rating to G. Giphy is mostly user contributed content, some of the users like to submit very challenging content so I'm sticking to the G rated content. Then we've got our separator for parameters in our URL and then finally we've got an API key. API keys are a way of telling a service like Giphy who is making the request. Normally, we would go and ask Giphy for an API key of our very own and we would use that in all of our requests. This is a very old one that Giphy used to use for everybody. Now they have individual ones and we'll go over getting one when we start to build our example application. Anyway, having said all that that's our Giphy random URL and we use it here. So, we're saying please open this URL using the GET method. This flag here true means make it asynchronous. We could take this to false and make it synchronous but the whole point of AJAX is that it's asynchronous. So, we'll do that, make it asynchronous. Then we assign a function to onload, and this is what we want to do when the request has completed. So, the first thing that we do is get a reference to our image, remember there was an image in our HTML with an ID of GIF. Oh yeah, I'm in the camp of people who say GIF no JIF. So, I'm sorry if that really bugs you. Then we want to get the actual response that came back from the server for our request and that's in a property called response text. Then what we do is we turn that into a JavaScript object using JSON parse. So, like I said we'll be having a little look at JSON and how it works very briefly in one of the coming lessons. But the point is that we can turn the response into a JavaScript object and we assign that to response data. Then we get something called, image original URL, from the data part of response data and assign it to the source attribute of our image. Gosh! This to get down here, remember here is our image, it has an ID of GIF and here is it's source attribute, currently set to nothing, but we will assign this value to it. I'll also be taking a look at the Giphy API documentation, so you can know where to find that information about what's inside these responses, because I know that seems just like a random and mysterious list of attributes there. We'll also assign on error attribute. So we say, "Oh, this is going to be a function", if something goes wrong we're just going to say, "Show an alert," and say, "Oh, that was an error". Then finally we send it. So, this is where the request is actually sent and we hope once it's been received and the responses sent successfully, then our onload function will be executed, and then our image will have a source attribute assigned to it, and we'll be able to see that in our browser. So, now that we've seen all of this, let's take a look at it in the browser. Okay. So, here's our little test AJAX page, Giphy AJAX request. Here's out Load Image button. So, if I clicked that. There yes. It's pretty much what you'd expect to get if you ask for a random image from Giphy, and we can keep on pressing this button to get random images back. Yeah, and so I can keep on loading these all day. Hello Professor. So, you can see that the Giphy API is sending us references to images that we can load into our browser. So, just to recap, when we make an XHR request we start by executing open on our new request, we assign onload and onerror, which tells the request what to do when it succeeds or fails. Then finally, we send the request. We've seen that implemented in our code, we can see we make a new request first, then we open it. We assign a function to onload, this is what we do when the request resolves successfully. We assign a function to onerror, what to do when things go wrong. Then finally we send it. So, that's a very short and fast example of how we can make an AJAX request.
4. Public APIs - what you need to know: Okay. Welcome back to our intro to Ajax everybody. In this lesson, we are just going to do a quick run through of definition of terms and make sure that we're up to speed on some fundamental concepts that we would need for the rest of this class. So, how to use an API and the first thing we need to talk about is well, what's an API? And then we get to do a little JSON refresher because JSON is the data format that's typically used to transfer data between clients and some web API and then we're going to go off and get out API key for our news service and then we'll check out the docs for that service so we have a bit of an idea of how to use it. But first of all, what's an API? Well, it stands for Application Programming Interface and really it's just a place that we can send requests to for data. So, I can say "Please send me all the photos that look like dogs" or I could say "Hey, please save and store this new photo of this dog." We can also receive responses like it'll send us back a big bunch of photos of dogs if we're using some kind of photo API or a picture API like Giphy or if we're sending a request to save something, it might come back and say "Hey, I saved it. Everything was good" or it might say "Hey, there was an error saving your dog photo," and then we can work out what to do afterwards. And an API is a really super general term. Any kind of third party library that we use has an API. The web interfaces that we're going to be looking at during this class, like very low level socket interfaces. All of these things have a defined way of interacting with them and now we're going to have a little fast refresher for JSON. It's incredibly widely used but I know that not everyone has actually used it or is familiar with it so I'll have a quick look at it now, including playing with some code. It stands for JavaScript object notation and what that really means is it's a way of taking some string formatted in a certain way and turning it into a JavaScript object and then we can do the same thing. We can take a JavaScript object and turn it into a string and these strings are super handy for sending between an API and a client like your browser because it means that we've got this stream going backwards and forward that we can convert into a Java Script object. It is very very easy to format data in that way because it makes it very low effort but also it's very easy for us to use. It's a format that we can edit ourselves so that we can read easily and it's a very intuitive form of data to use. And so let's take a look at that already in some code right now. Okay so, here is a little file that's included in the project resources for this class. It's called jsondemo.html and all I've got here is a tiny little bit of HTML down the bottom with a button that does something, JSON demo when it's clicked and here is our JSON demo function and we can look at that in the browser. We click the button and some stuff gets printed to the console. And now what we're looking at here is I'm using an ES6 multi-line string set. That just means that we can use this as a back text to define a string that spans over multiple lines and this is what JSON looks like. We're going to wrap the whole thing up and some curly braces and then we are going to have a key value or a key name followed by a value and keys always appear as a "string" in quotes like this and then the value, well it might if it's a number it won't be quoted, if it's a string it will be quoted, the value might be an array or might be yet another kind of object. The point is that we can take this string, give it to the JavaScript built in object JSON and ask it to pass our someJson string and turn it into some object and then we can access the properties of this object individually just like a normal JavaScript object. Now we can log all of these individually to the console. So let's head across to our browser, JSON demo, click "Please check the console" and I click it and lo and behold, here we have all our little values coming out on the console. great. So, of course if we go and try to, I'll just uncomment this, of course just to show that there's not some peculiar string interpretation magic happening here, if we go back to our someJson string and try to access a property from that and hit refresh and then click the console button and if any we're getting undefined by saying this thing doesn't have a string property because it's just a string and that value is undefined. Now of course it goes the other way as well, let's say that we have this new object. We're going to call new JSObj, object, and in the normal JavaScript way we give it a name and then a value and keep on doing that. We can define an array of things of course and then we can go and log that to the console as an object and of course the browser will print that nicely for us, being very helpful and then we can go and turn our object JSobj into a string using JSON stringify, new JSobj and so if we check that out in the browser or reload again. And here we can see that our object has been first of all printed out because I just did like console log and it's been broken out nicely by the browser but also we've turned into a string using JSON stringify and you can see we've just got this very big string here and this is the thing that we would send over an API or in an API response or a request because it's easier to send a bunch of characters over the wire but it's more work to send an actual object of the wire in its way. And so that's why we use JSON. It's very convenient, it's very readable and intuitive for us to use and it's now the default standard for communicating with an API of the web. So, we have seen what JSON is, we have seen how it works. Next we need to get an API key for the API that we're going to use. Now, remember that an API key is unique to you. It's a thing that you have to use in your quest to an API. Assuming this is some public API and it's not one that you've implemented yourself on some server somewhere, but you get your API key, it identifies you, that way the API knows if you're making 100 billion responses or requests a second then you're probably some kind of trouble and they'll cut you off but it's a way of identifying you when you make your requests. And we're going to be using newsapi.org to get our headlines from, I was originally hoping to use the Google News API but I see that it's in a semi-shutdown state. I don't know how long it's going to be around for it's been semi-shutdown for quite a long time but I think it could disappear any moment. Anyway, we are using this api.org and to use them we'll have to get an API key so head on over to newsapi.org. We can see we are presented with this page and the first thing we see is get API key. So, go ahead and fill that out. I'm Luke and my email address is terribly done, fabish@. This is like a nonsense email address guys. And I may have to use another password. Am an individual, I'm not a robot. I agree to the terms and yes, we will use an attribution link on our page eventually. Submit, and no thanks, I won't save that. And so finally, we have our API key. This is the value we need to use in our requests to the newsapi.org interface. So, now that we've got our key, we better check out the API documentation. Assuming it's not your API, if it's an API that you've written yourself then probably you know how it works. And that's also assuming that the documentation exists and is coherent and is up to date. It is a public services. Sometimes they're very well documented and sometimes they're barely documented. So, let's go over and check out the documentation for the news API. And really what we need to do is just reload that page and the documentation is pretty decent really with these guys. That's simple. We are going to be using the top headlines requests and they provide a lovely sample requests using our API key already. They're saying "Hey, this is how you make a request to our API" and this is what you're going to get back and then give you this lovely collapsible structure so you can see the top level, we've got like three things, status and the number of results and then they give us the articles and inside the articles well, it's this thing a source and the author and a title and a description and so on. So, that's really quite nice. And then they go and document what the parameters are, when they can be set to and then finally their document, their response and what's inside the response. So, this is pretty straightforward and pretty easy for us to use. Now in the next lesson, we are going to have a look at the three kind of main states we need to cater for in an Ajax request and we'll start using this API. So I look forward to seeing you in the next lesson and remember if you have any questions or would like anything clarified please let me know in the discussion area and I'll get straight back to you.
5. Three fundamental AJAX states (we'll start by waiting!): Okay everybody welcome back. In this lesson, we're going to be looking at the three fundamental Ajax states that we need to cater for when we are programming an Ajax client or dealing with requests and responses with Ajax. Now Ajax being like a network protocol, there is like a bazillion different states that the actual low level network connections can be in, but there's three that we really need to look after ourselves and that client code which is waiting. So, you've sent a request and the users are waiting for the request to like finish or do something. We need to show them something, to tell them that things are actually happening and then finally success. Well our request completed successfully, so we should do something with the response. In case things don't work, we should handle the error as well. So, time to wait. So what's this business with waiting? Well, we need to tell the user that their action has had an effect of some kind. Because if they click a button and nothing happens, then they're just going to like keep on clicking that button like crazy probably. We need to really tell them that, yeah, your action has been noticed and when doing something about it even if you don't have the results yet, and like I was saying, feedback helps users. It helps them know that something's happening because get it asynchronous requests can be very slow sometimes. Well, not super slow like minutes but they can be slow enough for a user to start scratching their heads saying, "Well what's going on? I don't understand. I clicked the button, nothing's happening." What we really need to do now is start implementing a request to our news API. So we've got our API Key, we have checked out the docs. So, I'm going to be implementing a request and showing the user a little weight spinner. We won't do anything with the results just yet, that's for the following lesson, but we'll see how we can do that right now. I strongly encourage you to code along with me, because in our project resources, we have giphy-news.html, which is skeleton html, that includes a link to some predefined CSS, which will lay out a page a little bit and apply some fairly minimal styling to it just to help us get started. Also and it seems that there's something called news-api.js, in there as well, which is just an empty JavaScript file. That's what we're going to fill in. So, you've got everything you need to code along as well. I think that's a great way to learn and strongly encourage you to hit Pause whenever I've finished doing something and implement it as well. So, just to give you a quick rundown of what HTML besides including some JavaScript and CSS, we've got the body, we've got H1 going as well us, you know what we're looking at. We've got empty div, with an id ajax-wait and class waiting. The animation and the spinner and everything is entirely done in CSS. So, check out that file if you are interested to see how it does that. It's basically a div with a dashed border. It's spinning around and it has a predefined size and position. So, that makes it easy to display and hide. Then when we get into our main section of our page, we've got three divs; error, headlines, gifs. We'll be filling in each of these as necessary. You can see that our html has provided spaces for our three kind of states here. We've got our waiting div which we'll display when something's happening but not finished yet. We've got an error div for when things go wrong and these two are for filling in when things go right. So, let's get started implementing our JavaScript. So the first thing I think we want is a function and we'll call it show headlines. Off to a great start. We want to make sure that that function is called when the page has loaded or completed loading. So, we'll say straight off the bat window.addEventListener, Correct. Here is where we want to make our API request. So, I'm just going to add this in quite quickly to avoid you the pain of watching me spend many hours doing my typos. So what we want as the first thing is well, where should we send our request to? We know that from looking at our documentation and here, we are back at the News API documentation page. We know that we can use this top headlines endpoint right here. That's great. We'll have that in there. Then we need to have a little question mark to say that there are some parameters on our URL and that our- well, we'll search within the US. Our next parameter will set the category to entertainment. I'm using entertainment because the general use is kind of a bit grim sometimes. I thought I'd keep it large and then finally we're going to set out API Key. This is my API Key, please don't use my API Key. We don't want to get the news or people mixed up with that. So, there it is. We've got our URL. Now, what do we need to do after that? As we've seen in our previous lesson, when we were demonstrating the Giphy API, we need to create a request and then we need to open it. Say, request open. We're going to be using GET all the way through here. We're not going to be storing any data on these APIs, so we're going to be using GET so that we can get data from there. Then finally we want this to be a asynchronous request so we say True. So, the things we need to set of course are say onload, which won't do anything at all right now. Similarly, we will have to have some kind of error handler, what's we do when things go wrong. We'll set that also to an empty function for the moment. But what we do want to do is, of course, send our request and then at this point, we want to show our user that something is actually happening and implement our wait functionality. To do that we can set our ID or our div rather of Ajax Wait to just fly. Currently it's hidden. It's got a display of none. We can set the display to block. So, we'll say very quickly and say document.getElementById('ajax-wait') 'block'. Now, we don't really want to do this sort of thing in the middle of our show- Headlinescode but this is something that will hide away in another function very soon. But we just want to make sure that we can actually do something. So, let's get out our browser and give that a whirl, and there it is spinning away happily. As you can see it's still there spinning. Our request has obviously been made and sent and we're displaying our spinning gif. However, well has the request completed? Is there an error? We don't know. We better do something about hiding this thing once we've finished our request. So, here we go in our function and, of course, we want to set that to none now. Very good. So, let's get back to our browser reload. As you can see as I'm reloading, we display a little spinning div and then it goes away again because we completed our request. Did we complete successfully or unsuccessfully? Who knows, that's log success. Look at that and here I will say error reload. Look at our console, success or very good and success. So, we can see that we are setting up our URL with some parameters on it, creating a new XMLHttpRequest object. We are opening it, saying we want to perform a GET HttpRequest, with our URL that defined. We want it to be asynchronous, when our request completes successfully, we should execute the onload function. Which is defined like this so far. When there's an error, we want to do this. Finally, we send it, so that one of these will be execute. Finally, we want to display [inaudible] to give the user some feedback, that their action has actually had an effect of some kind. Now, the next tiny little thing I'm going to do is just hide away our document getElementById blah blah blah cols there. Boom, there it is. So, we're basically using a function that takes an ID and a display value, getting the element from the document, checking to see that the element exists and setting the display to whatever was passed in. Then we've got a show and hide function, one of them passes in block to setEleDisplay the other than passes in none. Finally, we're free to go down and say hideEle('ajax-wait'), and then do the same thing there. Oops, and then we can say show. We'll test that in our browser again, reload, that one took a while. There you can see that we've displayed our little white div, our white feedback and then we've completed successfully and removed our wait div from the page. Now, that's all well and good, but you can see we are not yet showing any headlines in our page, which is, what we really, really want to do. So, in our next lesson, we'll be working through the success case where we read the response from the API and write out the individual headlines to our web page. As always, if you have any problems, things aren't working for you, let me know straight away in the discussion area and I'll help you out as soon as I can.
6. Reading headlines from our news API: Okay then. So, in this lesson, we are going to check out how we can finally read the results of our request for headlines from our news API. We've seen how we will wait for them and we know that our request completes successfully, but we haven't done anything with the response yet. So, today we're going to see how we can read the results. We'll see how we parse them, already seen how to do that in JSON but we'll work through that anyway. Finally, we'll actually get on to displaying our headlines. So, here we are in our in JavaScript code and if we go and look at our own load function. You can see, as you recall, we simply hide our little spinner and then log success to the console. Not super exciting but what we can do instead, probably the next not so exciting thing but more useful, is instead of logging success we can log request responseText. So, now, responseText is all the stuff that the API sent back to us, and remember this is a big stream in JSON format, so it's not a JavaScript object we can do anything useful with yet but we can blurt it out to the log and see what's inside it. So, I'll save that. Head back to the browser, reload. It's taking a while. It's loaded now and you can see that indeed we've got something back from our API. Says, "Status OK, total results 20," and then it goes into articles. You can see you've got a square, bracket at the beginning there which means it's an array and then it just goes on off the edge of the console line because it's quite large. So, at this point I'm thinking, "Man, I want to see what's inside that response." So, let's go back to our news API documentation and while we can go down to the response documentation here and see, oh yeah. We get a status, results, articles. That all lines up with our expectation from what we've seen in our console and then inside the article's array, we've got source, author, title. This is the headline or title of the audio. This is the thing that we want to play with, right? So, let's go back to first that web page, and now our code and instead what we'll do is we'll say newsData. User sign JSON.parse. Yeah. So, we can do that and just so that we know something sensible is happening, let's print out our array of articles. So, we'll take our console log from here and grab our newsData articles. Again, this is not like a super helpful thing but it will verify to us that we do have a JavaScript object and we can see the articles. So, reload, and good old Firefox, I mean Firefox here has given us an array that we can go and look at here. Well, and we can see the first thing is something about Rihanna and something else is about the Avengers and Kylie Jenner. So exciting. So, now what we can do is have a plain old full loop and say, "For var articleIdx is zero." Let's say articleIdx is less than- length articleIdx, we'll do a plus plus. I'm not a super massive fan of those kinds of operators but keep life simple. I can go for that now. Okay. So, I've got a little full loop and finally, I'm not satisfied with that formatting. Like I said, let's now print out exactly one article, right? So we'll say news articles. We'll print out the title of each article. We know there's a title in there. So, let's try that. We'll go back to our browser and what we log now is a bunch of articles or article headlines to our console, which is great. So, we're getting closer and closer and closer to what we actually want. Now, the next thing to do is to put all of this into the web page instead of the console, and to do that I'm going to do this weird trick. We'll call that output is an array. So, what we'll do is we'll build up an array of HTML that we can jam into our articles or our headlines, div. So, remember we have this div with an id of headlines and we are going to stick a bunch of stuff into it. The very next most simple step that we can do is say, "Output.push the title," and then finally, we can say, "Get by id," and that was headlines, inner HTML, user sign output.join, like so. So, what are we doing? We're getting our headlines div. We're saying we want the HTML, basically everything inside the div to be equal to our output array joined up with a bunch of new lines. So, we can go and take a look at that and then we get a bunch of headlines all in one big unbroken mass in the middle of our page there. Again, so far so good. But we run it, it is a little more nicely and each time that we do the headline let's put it inside it's very own div. That will make them appear on new line and gives us an opportunity to apply some styling to them as well, because look at some predefined styles ready for our articles. So, we'll open a div. We'll put our article, title or headline inside it and then we'll close that div, and again we can get the benefit of that just by joining our output into one big long string and assigning it to HTML on our headlines' element. So, let's go back to that and we'll reload, and you can see I've got a little line above and below each of the article headlines. Just to separate them a little bit, and you can they are appearing individually on each line. So, we're getting closer and closer and closer to how we want them to actually appear. But remember, we do want them to be cliquey. You'll want to have to click on them. So, the next thing we can do is put them inside and a tag. So, we'll say, "a href equals. So, we can put them inside in a tag like that. Now, when we go back to our browser, we reload and they are all clicking which is great but when we click them, they don't really do anything. But now, this is getting a little busy inside these onload function here, and I really want to put all of this inside a function of its very own just to separate it out a little bit. So, I am going to go up to top here and I say am trying to makeHeadline. You can see how may I have thought of this before. And we are going to have here, we will have our title, that's all we need to know really. And, yeah so put all of that in there. And this just becomes title. And then what we want to do is return our output. So we can pass output in, and return it back again with a few more things inside it. So, now we need to use our makeHeadline function. Boringly I deleted that very useful bit of text. Anyway. There it is back again. Let's test if that works. Reload and of course I need to include our output as well and say output is assigned there. Okay, finally we can do that, and okay. So, this is what we need here, and make sure everything works as expected. And it does, so all well and good. However, we need our makeHeadline, we need a little href to do something when it's clicked. So, we will say onclick equals, let's just say log. Boringly we have to start escaping quotes here, clicked. Just to make sure that this is going to work for us as well. Okay, save that. Head back to our browser, and we can say click, click, click, click, click. We can see that that is executing there. And we could be forgiven for thinking that the very next thing to do is decide well, let's just put our title in there. Like that right? Okay. So, let's just check. See how this works. Give this a reload. Finally, great, we are showing all of our headlines here, and let's choose one very carefully to click on, and excellent that displays the headline in our console, and the way we want. We click on that line, syntax error, a missing bracket, close bracket after argument list. So, we can see that I chose one of these headlines, it has a quote in it. And of course, we are using single quotes here to enclose our title. So, unfortunately we are going to have to do something about the quotes that are inside the title. And the quick and easy thing we can do is a replace all of our single quotes. And all of them. So, I have put a g on there to say, get everything you find in the string, not just the first one, and then we want to replace that with a backslash, and because it's a backslash we need to do a double escape of the backslash. Which is super boring. I would use double quotes for this. Right, so what are we doing here. We are saying, what we want to do is replace every single single quote, with a backslash followed by a single quote. So, we are escaping them basically, saying this single quote has no function in this string. It's just for displaying. I mean we use two backslashes because we are saying don't do the escape now, do the escape in the actual string that gets printed out. Gosh, and so what we need to do now is head back to our giphy news, web page, reload. And let's choose something that has no quotes in it. So, there's one about Karlie Kloss. We can see Karlie Kloss is printed out to the console, happily. What about Avengers Infinity. See here's our single quotes appearing in the console. Happy days. And finally have that something with double quotes in it. Oh dear, unterminated string literal. So, that's going to be causing problems, because of the double quote. There's going to be one last thing that we are going to do here. We're going to say encodeURIcomponent. Now, this is something that's built into Javascript, which is for preparing a string to be used in a URL but gives us other benefits such as encoding many of the strings that cause, or encoding many of the characters that cause, us problems. However, single quotes don't get dealt with by encodeURIcomponent. Head back. We would give our page a reload, click on this most troublesome title and you can see what we have got here. The spaces have been turned into percent two zero, which is hexadecimal value for a space, and our other problematic characters have also been converted. You can see the double quote is now percent two two, and we have still got our single quote there that's been escaped with a backslash, which is why it's appearing happily in our console. And the point is that we have now got a value that we can feed into the giphy API for retrieving a bunch of images that match Drake hops on N*E*R*D and Rihanna's Lemon Remix. So, that's as far as we are going to take that for this lesson because what we have done is successfully send a request to the news API. We have received a response. We have processed the response, and put it onto our web page. We are taking action when the response or when tittle is clicked. And the next thing we want to do is send that to the giphy API to get a bunch of images back. As always, if you run into any problems during this lesson, doing any of this yourself, remember to please let me know in the discussion area and I will help you out right away. Otherwise, I will see you in the next lesson.
7. Dealing with AJAX failures: Okay. So that brings us to the last of the three Ajax states that I talked about, the ones that we need to take care of if we have the use Ajax well and that is failure. What do we do when things don't go right? Well, this is all about handling errors obviously. So, if we send a request off and the response indicates that it was not successful for some reason, and we should let the user know that things didn't go right. That what they were trying to do maybe it wasn't successful. Should they try again? This is all part of making sure that the user understands what outcome that their action has resulted in. Once again, this is going to be a little codealong. Please, do once again copy the coding as you go. It's just a great way to learn and much better than sitting and watching because obviously I'll be doing this as well, at the same time. So, let's hop back into the code, and as a refresher remember that we have this div right here with an id of error. This is the one that we are going to use to display out error message, and it does have some special starting predefined in our CSS to make it look a bit red and an angry like an error. It's also set to have a display of non [inaudible] , so that we don't normally see it. So, here we are in our Javascript code, and here is our show headline's function and just lost there for a minute. Here we are in on error. So, we assign a function to the on error property of the request. The first thing we do is hide the white teeth, so that the user knows that their request has completed. So, the last thing I'll do is get our error element, and set it to an error message. There we go. The last thing that we need to do is show an element, which is the error element. So, here we are. I'll just reload the file. Web page, and you have to click on this one, and I can see is still behaving as it did before. Now, headline is appearing in the console and all is well. We're not seeing any error message that if we go and turn our WiFi off and ''Hey presto, I'll do a reloaded''. We see an error message just not the prettiest error message in the world, but we can say that we're indicating quite clearly that there has been a problem and we are catching the fact that there was a problem and telling the user about it. Good onto a reload, and there we have our headlines back again. So that's it, very quick demonstration of how we can show when things have gone wrong without Ajax request. In our next lesson, we will go on to putting everything you've learned so far into action by signing up for the Giphy API. Checking out the docs and then fitting our headlines into the Giphy API to show some images.
8. Access the GIPHY API with your awesome new AJAX skills: Okay. So, it's time to put your new skills into action. It's practice time. Practice will help you really consolidate everything you've learned so far. We are going to use the GIPHY search engine. We'll take the headline that we have, or one of the headlines that we might click in our web page, and feed that headline into the GIPHY image search, and then display any images that match that headline. We are going to do this one step at a time. So, I'm not saying, "Hey, just go and do that right now." The first thing we need to do, is sign up for an API key at GIPHY. So, head over to developers.giphy.com. Click the Log In button. Click Join GIPHY which is in teeny tiny writing at the bottom of the log in form. Head back to developers.giphy.com, because once you've joined up, I think it leaves you at giphy.com. Click Create an App. Then fill out the form to create the application. Then it will show you your API Key. You'll be able to use that in any calls to the API that you make. I'm going to do that right now. I'm sure you've signed up for online services before. So, there's not going to be anything super challenging here. But, I still encourage you to go and give that a try before you watch me do it too. Okay. So, here we are at the GIPHY developers page. It's probably everything you'd expect from GIPHY. So, I'm going to click on Log In. I'm going to click the tiny GIPHY Join GIPHY link. I do find their sign up page to be quite distracting. I'll use my luke.fabish@lukefabish. I'll set my username to lukefabish-gifs, and my password would be awesome, something around that. There we go. I don't know if you can hear it over the microphone. This page is making my laptop's fans spin up and whirl like crazy. So, I'm going to click Join and get off of this as soon as possible. I'd say don't save that. Okay. So, we've joined up and now I get to click Create an App. Okay So, we're going to say, All the news that GIPHY can give us. I'll call it GIPHY News. I'll click Create App and boom. There is my API key, which I have selected and copied. So, that's the key that we can use to make API requests against GIPHYs API. Now, that we've done this, we better go and review the GIPHY API docs. So, we can find those at developers.giphy.com/docs. There's just some left hand navigation. Check out Technical Documentation. Click Search Endpoint. Then you'll be able to review their parameters in the requests and you can see what's included in the response from those requests. Part of those responses is something called the GIF Object I believe. So, check out Schema Definitions, again, in the left hand navigation. Click the GIF Object. Most of all, don't worry. I'll be stepping through using the GIPHY response, particularly the GIF Object, which is kind of large. I found myself a little bewildering. But, we'll do that together. Okay. So, you don't have to type that URL into your address bar. We can just click the Docs menu item. It's over a cheerful and GIPHY-like again. But over on the left hand side here, we have Technical Documentation. Check that out. Here's our GIFS Search. So, we go to the Search Endpoint. You can see the host is api.giphy.com. Here's our path and it tells us what should go into the request. Our API key, of course, queries, which we'll set to our headline, and a few other things that we, or the other one that we'll actually use is the writing. We'll set it to G to protect ourselves from some of the more challenging GIPHY content. The response tells us that we get something called data. This Is going to be which we'll have an array of GIF Objects, Pagination, and something called the Meta Object. The one that we really need to check out, oh, man my fan is going wild at the moment, is the GIF Object. We can just click it here to go and look at it. But, I said it's in Schema Definitions, and it is GIF Object. Here we go. It tells us that we've got to type an ID, a slug, lots of things actually, like lots, and lots and lots of things. Includes most of all images. So, we have to go and look at the images object. This is where our image data actually resides or URLs to find the image. There's a bunch of different types in this response. There's fixed height, and fixed width, and fixed width still, and fixed width downsampled, and so on, and so on, and so on. You'll find that we get way down to original. Okay. So, this is the one that we're going to use. So, we'll go and find our original, which is another object, which has a URL. We would just use this URL to display our image. Like I said, this is a lot of detail. The thing that we want is buried quite deep in the response. I'll show you how we can access that in our code. So, one step at a time. How are we going to do our GIF Search. So, this is the bit where I want you to fire up your text editor, go from where we've left off with our other steps so far, and basically, make a copy of our show headline's function that we have already and call it Show GIFs if you like. We'll replace a few things in there to get started. So, you know how we build up the URL with some parameters. Now, our URL should be this, http://api.giphy.com/v1/gifs/search. We should use the parameters as follows. The rating should be G, Q should be the headline, and I'll talk about that just in a moment, and the apiKey should be set to whatever your API key turned out to be. Then assign a function to onload for your new XML http request. Just make it print the results of the API request to the browser console. Then the onerror property can be pretty much just like it was before with a slightly different message, right? There was an error getting GIFs instead of there was an error getting headlines. But the thing that I really wanted to come back to is for the parameters. I've said Q should be equal to their clicked headline. So, you know where we construct our headline link. Here it is right here. We're constructing our link. We've got onclick=console.log. Change that to the name of your new function, Show GIFs, if that's what you decided to call it. We'll pass in our URI encoded title. Then that will be available to you to pass into the GIPHY search request. So, please do have a try at implementing that. Like I said, we can start with a copy of our Show Headlines function, modify it using the information you have here. Once you've done that, I'll go through how we can start displaying individual images in the web page. So, here we are back again and I am now going to make my Show GIFs function. So, like I said, I really, super strongly encourage you to have a go at this on your own before following along here. Just because that's like super good practice. I'm going to start off with a copy of our show headlines function and over the top of the last curly brace, fatal miscalculation. So, what we want to do, let me call it Show GIFs. Okay. So, we've got Show GIFs in our headlines URL is going to become our GIFs URL. GIFs URL, I'm going to use it down here. Okay and I'm going to replace that with the GIPHY API End of Point. Then I want to set our rating equals g. I'll say q is equal to, well, we need to have that past tense. I'll say, I'm just going to call it Search Term, because we could definitely use this again in the future. So, we're going to be searching, we could use it for searching more for more than headlines. Okay. So, there's our URL with parameters. We're making our request as before. We issue a Get since we're asking for information and not trying to update information on the server. It should be a post. Now, we get into defining our onload. Again, they'll hide our weight element. We'll say, well, yes, so, we'll just send this to the console, right? Like I said, we would console.log. The rest of it we can get rid of for now. On error we will say, "There was an error retrieving GIFs. Please try again." So, the one last thing we need to do is make sure that this thing is called when one of our headlines is clicked, so we'll go back up to where we construct the headline and we'll say, "showGIFs." There we go. So, I'm going to reload our GIPHY News page. Let me click a headline, and you can see our white is displaying and then disappearing. Then you can see we've got all of this stuff here from GIPHY, so this is the response from GIPHY's API. As promised, it starts off with a data key, which is an array of the GIF Objects as we saw defined in the GIPHY documentation. So, here we are back again at our show GIFs function, and I'll approach this in the same way that we did previously. We'll work through it a bit at a time just so that we can slowly navigate towards getting this stuff out onto the web page in a format that we want. So, the first thing I'll do is define an object. I'll call it gifData equals JSON.parse (req.responseText). Let's output that instead, gifData. So, I'll save that, head back to our browser, reload, click a headline and see we can see that this has been broken down now into an actual object and being printed nicely for us by Firefox. We've got three fundamental parts of our response. We've got data, we've got meta and pagination. Pagination is information about how many results there are, how many results are up a page, and it allows us to page through big sets of results. But, we won't be doing that, we'll just be doing the first one, the first page of results. A bit of metadata tell us about our status, 200 okay, the message is okay, and gives us response ID, and then finally, data with our GIPHY objects, which are all of these things. If we go looking into one of those, we can see that that stuff that we saw in the documentation is here. We're interested in images. Let's go down with the images, and then finally after all of that, we can see there's an original with the URL. We can use that URL to actually look at a GIF. I wonder what that GIF is. Let's click it. Very good. So, let's start using that data. So, instead of just logging the GIF data, what we can do is set up another little for loop. I'll say for, say it's less than the number of elements in our response. So, I'll say "gifData.data.length." I will say, "gifIdx", again for brevity using a unitary operator, not a fan. Then what can we do with this? Well, what we can do is we can say, okay, please show us data(gifIdx).images.original.url. My gosh, so I think that's correct. I don't remember exactly. Let's see what we get in our console. Reload it. Click a headline, and here we get a bunch of GIFs. Now, let's click one up, see what we get. I do find this mildly addictive clicking on these things to see what they are. Anyway, so now that we've got that, we've got everything that we need to start shoving images into our web page. But, how are we going to do that? Well, really what I want to do is create a bunch of image tags and put those inside our GIFs div because if you recall, our HTML has a div with an ID of GIFs, so I want to fill that up with images, each one with its source attributes set to whatever our gifData, gifIdx, images.original.url is such straight off. I know I'm going to want a new function for this. Let's make one up, addGIFImage like that. This is going to be something that adds our URL to create an image inside a container. So, our container is going to be that div called GIFs. Then we want all of this in there. Those funny sounds you can hear me making just me using commands. So, we've got a definition of a function to do that for us. So, let's go up to above show GIFs and create this function called function addGIFImage addToElementId and imgSrc. So, what we want to do is we create a new image, and we'll say, because we will ask the browser to do that for us to create a new image element, createElement of type img. Now that we've got a new image, we can say that's a source, and say newImg.source equals image source. What we want to do now is add this to our image, well a container for our images. We've passed the name of that container in here, addToElementId. I might just call that imageContainerId. That seems to be a more intuitive name. So, we'll say containerEle equals document.getElementById(imageContainerId). Then we can say containerEle.add. No, it's append. Thank you for reminding me. Text editor a newImg. We're pretty much done. So, what's going to happen here? Every time we look at one of these URLs, we need to call addGIFImage, and we're going to say, please make a new image element, set the source to this URL and append it to our GIFs container. So, our GIFs div. Let's see how that goes in the browser. Reload, waiting, and I'll click 'Will and Grace' Renewed. Okay, and look what we've got. Here's a bunch of GIFs appearing from GIPHY. They more or less match up to this new Will and Grace business. So, yeah and they're appearing like this side by side and the GIFs are appearing in this column format just again, because of the CSS I've set up previously for this. So, this is pretty good. So, let's look at another one, Bella Hadid and something or other, and what's going on here? Some things seemed to have changed, some haven't. I'm not sure our G rating is really working the way it should here, but we've got like loads more GIFs than we should have. What's happening here is, because we're calling this appendChild to our container, it's adding lots of GIFs to it or these images but it's not clearing the old ones out. So, we better do that before we do anything else. So, what we'll do again, let's just say document.getElementById, GIFs, dot, like that. So, that's saying, hey, everything inside our GIFs div set it to nothing, empty string. So, let's see how that works in the browser now. We'll reload this. I will click this thing about Barbra Streisand. I'm going to get rid of our console. Well, here's our GIFs. Wow, Prince Charles. So, we got some other Prince images here clearly, but we can see that these previous GIFs are being cleared out and we replaced them with all these other Princey kinds of GIFs. So, this is pretty much the application as we intended to build it. We've got headlines on one side, GIFs on the other that match headlines when we click them. We're getting all of this data from two different APIs where we get the headlines from the news API. We feed a headline into the GIPHY API to get a bunch of matching GIF images.
9. Time to say goodbye!: Okay. Everybody, that's it for our class. We've covered a lot of ground. We have seen how we work with JSON. We've seen how we access public APIs, how we can use AJAX to make requests, read responses, and handle errors, and of course, we've built our little web page for showing gifts that match the world's headlines. Please don't forget to post your project into the projects' area. I love to see the work that students do, and, of course, I'm here ready and waiting to help you if you run into any problems while you build your project. Otherwise, please don't forget to follow if you'd like to see more classes like this and I look forward to seeing you again in the future.