JSON and AJAX Tutorial: With Real Examples

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone in this video we will learn what json is what ajax is and how to use these two things together to pull new data into our web pages on the fly let's begin by looking at a demo of the finished product that we will be building together in this video so on this page we have a heading and a blue button and when i click the blue button info for three animals gets loaded in so info on meowsie the cat barking the dog and purpose the cat is loaded in and if i click the blue button again whiskers woof and fluffy get loaded in and if i click it one more time the button disappears and kitty pupster and tux appear now using javascript to respond to click events and manipulating the page is nothing new we've already learned how to do that in previous videos the point of this example is that this content is being loaded on the fly what do i mean by that well if we view the source for this html page so view page source notice that we don't see any of those sentences about the animals this is because when this page first loads it doesn't contain any of that data instead i've used javascript to say that when this button gets clicked the web browser should go out onto the internet download a tiny bit of new data from a different url and then again i use javascript to output that data into this empty div and onto the page and all of this happens on the fly without a page refresh this might not be the most exciting project in the world but i promise it will teach you the basics of json and ajax let's get started alright so behind the scenes i just removed all of the javascript from this page so now if i click the button absolutely nothing happens so now you and i can start from this same beginning and move forward together so if i jump over to my text editor we will review this html a bit later in the video but it's not important for now all that is important right now is that you create a new html file on your computer so you can follow along and be sure to include a reference to a new javascript file if you're not sure how to do that i recommend watching my javascript in half an hour video uh but for now let's keep things rolling so i'm going to jump over to my brand new completely empty javascript file and let's write some code now we'll need to learn how to walk before we can run so what i mean by that is before we learn how to tell the browser to go download new data from a different url before we do that let's first learn about the most common way of storing and working with data in javascript which is json it all boils down to two things objects and arrays let's talk about objects first so let's say i want to store data about a cat and i want all of this data to live within one variable or one object so i could create a variable and name it my cat and say that it is an object and then i can assign it different properties and values so i can say that the object should have a property named name and then we assign it a value so maybe the cat's name is meowsalot and this object can have a different property so let's add a species property and give it a value of cat and let's add one more property named fave food and we'll give it a value of tuna alright so this is an object now if i wanted to access the cat's name somewhere else in my code i would just type my cat dot name and this would return a value of meows a lot or if i wanted to access the cat's favorite food i would just say my cat dot fave food and this would return a value of tuna alright so this is an example of how to access data that lives in an object now let's talk about arrays let's imagine i want to create a single variable that contains all of my favorite colors so to do that i would use an array so let's delete this and instead let's create a new variable i will name it my fav colors and let's tell it to be an array so we say equal and then a pair of square brackets and an array is just a comma separated list so i would list my first favorite color blue and then a comma and then i can include another value so green and then a comma and i can include another value purple all right so this is an array and if i needed to access the second item in the array so the value of green if i wanted to access that somewhere else in my code i would just type my fav colors square brackets and then the number one we would use the number one to access the second value because arrays are zero based meaning you would access the first value with a zero here instead of a one you access the second value with a one you would access the third value with the two so on and so forth all right so this is how you access data that lives in an array so to recap so far we've seen an object by itself we've seen an array by itself now what if we do something crazy and combine the two so for example what if we wanted to have a single variable that contained data for multiple pets we can do that by creating a new variable so let me delete this line let's create a new variable named the pets let's tell it to be an array only this time we don't want an array of simple text string values this time we want an array of objects so to define an object you just open up a pair of curly brackets so we could define our first animal or pet object within these brackets and then include a comma and then another object and then a comma and then another object you get the idea but including this much data on a single line of code can begin to look messy or complicated so instead let's drop down to a new line in between our array square brackets and then in between those two lines we can create curly brackets for an object and let's just create two let's say we want two pets or two animals to live within this array all right now let's actually define our objects so we can just copy the code that we have up here so i will copy these three lines into my clipboard and then within our curly brackets down here i'll just drop down to a new line and paste in so our first pet object in this array is meowzalat the cat let's paste those three lines into our second object only this time we'll change the name to barkey and we'll say that barky is a dog and we'll say that his favorite food is carrots and we can delete these lines we don't need them anymore alright so now we have a single variable that contains all of our data and i have a surprise for you you just learned json so the code that i have highlighted right now is an example of json objects and arrays nested inside each other json is just a popular and agreed upon format for sending receiving and storing data the json acronym stands for javascript object notation alright and as an example if we wanted to access barkey's favorite food somewhere else in our code we would just type out the name of our variable so the pets it's an array and we want to access data that lives in the second item of the array arrays are zero based so to access the second item we would say one and then it's an object so to access one of its properties we just include a period and then the name of the property we want and that's it so this would return a value of carrots as another example if we wanted to create html paragraph elements with sentences for each object that read meowzalot is a cat that loves tuna and barky is a dog that loves carrots if we wanted to do that we would just loop through this array and create an html text string and then add it to the dom now we will learn how to do exactly that step by step in detail a bit later on in the video but for now let's keep things rolling so we've learned about json now let's learn about ajax all right so we have a bit of json data here but in the real world you typically won't have json data just conveniently sitting in your javascript file like this in the real world you'd probably need to load json from a dynamic source like another url that is powered by a database so let's make it our goal for the remainder of this video to load the json data from this url i encourage you to follow along on your computer so you can either pause the video right now and type out this url or the easier option is to just copy and paste this url by finding it in the description for this video either way our goal for the remainder of this video is to use javascript and ajax to visit this url and download this json data on the fly so that we can use it on our web page okay so to get started let's jump back to our javascript file and let's delete everything we have and start fresh all right now the process of sending or receiving data on the fly without a page reload is known as ajax and we'll learn what that acronym stands for in just a moment now web browsers have a built-in tool named xml http request and this tool will do the heavy lifting for us this tool will establish a connection with the url that we specify and then it lets us send or receive data so let's create a new instance of this tool to begin we will create a new variable we can name the variable anything we'd like but i'm going to name it our request and then we just set that variable to equal a new instance of the xml http request tool all right now we just need to tell our variable to actually do something now the web browser will expect our variable to use a method named open so to specify that we just say our request dot open and this is our chance to say what we want to do so we will want to pass this open method to arguments the first argument is whether we want to send data or receive data in our case we want to receive data we want to download data so we say git we want to go get data if instead we wanted to send data to a server we would say post but we want to download or get data so we say git and the second argument that we will want to give this method is simply the url that we want to talk to so in this case that's the url that i showed a moment ago so again you can pause the video and type out this url or you can find this url in the description for this video and just copy and paste it but either way we want this url this is where the json lives so i copied that url into my clipboard and then back in my text editor i'm just going to paste it in as the second argument so this line of code will tell the browser to go to this url and get the json data now next we need to actually do something with that data so let's drop down to a new line we'll start with our variable so our request and we want to use a method named on load so this is where we say what should happen once the data is loaded so we're just going to set this to equal an anonymous function all right and within the body of this function we can do anything we'd like just as a quick example or a quick test let's log out the json data that we download out to the console so console.log and we can access the data that we just downloaded by saying our request dot response text all right so at this point we've defined our request the final step is to actually send the request so we just say our request dot send all right so if i save this and visit my html page in the browser and refresh and if i view my developer tools console perfect so here we see the content from the url that we specified okay so we logged that out to the console as a proof of concept now let's try to do something more useful with the data let's try saving it to a variable so back in our text editor within the onload function let's delete this line where we log it out to the console and instead let's create a variable we can name it anything we'd like i will name it our data and then just set it to equal the contents from the url that we specified so to access that content it's our request dot response text all right so now we have all of the data within our convenient new variable name now let's give ourselves a new example task let's imagine we only want to log out to the console the first pet object within this array of data so for example if i go back to that url currently the our data variable contains all of this content and just as an exercise let's try to log out only this first object out to the console so only the info about meowsie the cat so back in our text editor to do that we could drop down to a new line and say console.log we know that that data lives in our our data variable and we know that that is an array of objects so if we only want the first item in the array zero all right now if i save this and refresh we see that the only thing that got logged out to the console is an opening square bracket now this is not what we were hoping to see but let me explain why this happened by default when our browser goes out to this url and downloads this data it doesn't know to interpret this as json data right so by default the web browser doesn't know that this is an object or that the entire thing is an array of objects by default the browser is just interpreting this as plain text as a giant text string so back in our text editor when we said go into the hour data variable and return the first item in the array our browser says okay this data is just a simple text string not a traditional array and the first item in the text string if you treat a text string like an array is just this opening square bracket so that's why that's all we received when we tried to log it out to the console so obviously the solution here is to tell our browser to not view this as a giant text string but instead to interpret it as real json data as objects and arrays so back in our code when we are taking the response text or the content that lives at the url and saving it into our variable we want to first tell the browser to interpret this as json data so let's delete this and instead we can use a tool that our browser has built into it so json.parse and then within these parentheses we can include the content that gets pulled in from the url so now we can say our request dot response text so now the content that lives at that url will be passed through our browser's json filter so if we save this and refresh our web page and check out the console perfect we see only the first object on meowzie the cat and congratulations you just performed your first bit of ajax let's take a minute to talk about the ajax name so the ajax acronym stands for asynchronous javascript and xml the word asynchronous in this context just means in the background or not requiring a page refresh and if you're wondering what xml is xml is a data format that's very similar to json now we are not going to actually use xml we are using json instead so i guess you could call what we're doing aj instead of ajax right so it's asynchronous javascript and json because in recent years json has replaced xml as the more popular data format so json has become the industry standard data format but xml was very important for a very long time and overall xml was very important to the history of modern web development so that's why the ajax name sticks even though most of us are using json instead of xml and just in case you were curious this also explains why the browser's built-in tool is named xml http request we are technically using this tool to go out and download json not xml data but again xml was so integral to the history of web development that the name just kind of stays around even if that's not exactly what you're doing all right let's move on now at this point in the lesson we've learned what json is we've learned what ajax is and we've successfully pulled in data on the fly and saved it to a variable so now for the remainder of this video it's really just a matter of completing generic javascript tasks right so number one we need to respond to the blue button click events and number two we need to add new html to the page based on the contents of the our data variable alright so let's get to work currently our code is set up so that our ajax call to download new data runs as soon as the page loads and we don't want that we only want to go and download the new data if and when someone clicks the blue button so let's begin by adding an event listener for this blue button and then we will only run our ajax call when that event is triggered so to begin let's create a javascript variable that points towards the blue button html element so in my html file here is the blue button element and you can see that i've given it an id of button or btn so make sure that your html looks similar to this and then back in our javascript up at the very top let's create a variable we can name it anything we'd like i'm just going to name it button or btn and then i'm just going to select that html button element so document git element by id button alright so now we have this convenient variable that points towards that element now let's set up an event listener for when the button gets clicked so we just say button add event listener the event that we are listening for is the click event and then what do we want to actually happen when it gets clicked well instead of calling a specific function let's just open an anonymous function here all right and now within the body of this anonymous function we can just cut and paste our ajax call so all of these lines that we wrote earlier i'm going to cut them into my clipboard and then within this anonymous function i'm just going to paste in my clipboard alright so if i save this and refresh in the browser notice that my console is empty but as soon as i click the blue button now if i check my console we see that our ajax request ran successfully all right next we don't actually want to log anything to the console that was just for testing purposes what we actually want to do is add html paragraph elements for each animal that says their name their species so on and so forth so back in the text editor within our onload function let's remove this line where we are logging data out to the console and we could technically write code here that adds html to the page but in order to stay organized why don't we create a new function down at the very bottom of our file whose sole job is to create and add html to the page so this way our code stays organized so let's create a new function we can name it anything we'd like i'm going to name it render html all right we will build out what this function actually does in just a moment but first within our ajax call now we will simply call the render html function so render html and we want to be sure to pass this function the our data variable so that it can work with the data so within the parentheses when we are calling the function we can just pass in our data all right now within the signature for our new custom function within these parentheses we just need to include one parameter name we can name it anything we'd like let's just call it data for short all right and now within this function we can access the json data that got pulled in with ajax by simply saying data okay but let's start simple so remember this function's job is to add html to the page more specifically it's going to add html to this empty div element notice that i've given the empty div element an id of animal info so make sure that your html looks similar to this and then within our javascript up at the very top let's create a variable that points towards the empty div so variable we can name it anything we'd like i will call it animal container and then we just select the empty div so document get element by id and it had an id of animal info alright so now within our render html function we can target that empty div by using its variable so animal container and then we can use a method that is available to all dom elements named insert adjacent html let's say that we want to add html right before the end of this element so we say b4 end comma and then the second argument is simply the content or html that we want to add so if we said testing one two three save this and refresh the page and click the blue button we see testing one two three all right only instead of spelling out the text we want within this function call instead why don't we create a variable we can name it anything we'd like i will name it html string and let's set it to equal this is a test and then down on this line instead of spelling out the content we want let's just point towards this variable name so html string so if we save this and test it out click the blue button now the reason this is nice is now we are free to loop through the json data that we received via ajax we can loop through that data and just continually add on or concatenate to this variable it's hard to explain with words so let me just show you what i'm talking about so when we first define this variable let's actually tell it to just be an empty string all right and then on a new line what we're going to do is loop through our array of pet objects and do something once for each object in the array now if you've never used a for loop before i recommend watching my javascript in half an hour video it explains how for loops work in detail because in order to keep this video rolling along at a nice pace i'm just going to have to assume that you understand for loops alright so let's begin a for loop so i will begin as zero and we want the for loop to run as long as i is less than the length of our array so remember our array of objects we can access it with data so i'll just say as long as i is less than data dot length then we want to increment i each time the loop runs all right and then within these curly brackets we get to say what should happen for each item in the array so what we want to do is just add on or concatenate on to our html string variable so let's say html string we want to add on to it so plus sign equal sign and remember we want to create a paragraph element for each object in the array so we'll open up a p tag and then let's output the name of each animal or each pet remember we can access the json data with the word data so we'll say data which gives us the array of objects look inside that array for the first item so because i equals 0 to begin with this will select the first object in the array which is meow z the cat and then once the loop runs again i will get incremented so i will equal one and then when this code runs again this would obviously select the second object in the array so on and so forth okay but remember here we're trying to output the name of the object so just to put this into context if we look at the url of where we're grabbing the json from each object in the array has a name property so back in our code we can access that property by saying dot name and then let's say that that animal is a and then let's output their species property so data select whichever item in the array we've looped through and then we want the species property all right and then let's just add a period at the end of our sentence and close out the paragraph element so we'll add a period and we'll close out the paragraph element all right let's save this and refresh our page and hit the blue button perfect we see meowsie the cat barky the dog and purpose the cat but what if we click the blue button a second time well currently that will load the same three animals again which is not what we want we want to load new data for three different animals so check this out if i go back to that url that we are loading with ajax notice that the url ends in dash 1 dot json and if i visit a slightly different url of dash 2 instead of dash 1 notice that this url has information for three different animals so whiskers the cat wolf the dog and fluffy the cat so a big part of ajax is requesting data from the right url at the right moment so let's adjust our code so that the first time someone clicks on the blue button we load the dash 1 url the second time the button gets clicked we load data from dash 2 and the third time the button gets clicked we will load dash 3.json and we will hide the blue button so that it cannot be clicked a fourth time okay so to do that let's begin by jumping over to our javascript and up on the very first line let's create a new variable that equals one and then we can increment or increase that variable by one each time the button gets clicked so let's create a variable we can name it anything but i will name it page counter and we want it to begin with a value of one alright next on the line where we specify which url we want to download data from we want to make this url dynamic with the help of our page counter variable so here's the url that we are currently downloading data from and if i scroll to the right a bit here we see the dash 1 part of the url let's replace the hard-coded value of 1 with our page counter variable so we'll close out that first quote and then we'll add in our variable so page counter and then we will just add in this closing string all right and then if i scroll back to the left after this line of code where we send our ajax request we just want to increment our page counter value by one so we can just say page counter plus plus okay so now when someone clicks the blue button for the first time page counter will have a value of 1 so it will load the dash 1 json file right after that happens the variable will be incremented so then it's 2 so then obviously the next time we click the button it will load the dash 2 json file alright so let's save this and take it for a spin first click we see meowsy barky and per paws second click whiskers woof and fluffy and third click kitty pupster and tux and if i click the button a fourth time nothing happens and if i check the console we actually see an error message so you can see that it's trying to find the url that lives at animals dash four dot json and that file doesn't exist okay so if we know that the server only has animals dash one through three after the third click we should have this blue button disappear so that it can't be clicked any longer so to make that happen back in our text editor after the line where we increment our page counter variable let's just add an if statement and we'll say if the page counter variable is larger than three if that's the case if that's true then let's add a css class to the button element that hides it so we have our button variable that targets that element we will adjust its class list we will add a css class named hide me so you will want to add a bit of css to your page you'll want to add a class named hide me and set its display value to none or set its visibility to hidden you get the idea so if i save that and refresh the page one click to click third click the button disappears perfect okay now all that's left is to also output each animal's favorite and least favorite foods so for example if we look at the raw json data that we are working with we know that we have the name property and the species property we also have a foods property which in and of itself is an object that contains other children properties so the foods object contains a likes property and a dislikes property and notice that the values for the likes and dislikes properties are actually arrays so whiskers the cat likes multiple foods he likes celery and strawberries this is the neat thing about json it lets us nest objects inside of objects and it lets us nest a raise inside of arrays all right so for this last part of the video let's work on outputting the favorite and least favorite foods onto the page so back in our text editor let's scroll down to our render html function and on this line we no longer want to end the sentence and end the paragraph element so instead let's change this to read blank name is a blank species that likes to eat all right and then on the next line we will list and loop through their favorite foods so let's drop down to a new line and remember that currently we are in a for loop so the code we write here will run once for each object in the array so we just want to look for the current object's foods property and we want to look inside it for the likes property which is an array and then we just want to loop through that to list out all of their favorite foods alright so back in our code to loop through that array of favorite foods we will want to use a for loop nested within our current for loop so we'll say 4. let's use double i for our counter to loop through this nested favorite foods array so we'll say that as long as double i is less than the length of the favorite foods array so we'll say data the current object in the array that we have looped to and then we want to look inside it for the foods property and then inside that we want to look for the likes property and we want to find out how many items there are in it so dot length all right and then the final part of our for loop we want to increment i i by one all right and then let's open up a pair of curly brackets so now anything we write will run once for each of the favorite food items so we just want to concatenate them to the html string so we'll say html string add on to it plus equals and then we just want to add on the current favorite food so data the current item we've looped through foods likes and likes is an array itself so then we want the current item which is our counter i i alright and then after this nested for loop but still within our overall for loop let's be sure to add in the closing period in the closing paragraph tag so on this line we can just say html string and add on a period and a closing p tag let's save this and refresh so it looks like we need to add a space in between each individual food right so there should be a space between tuna and catnip and there should be a space between bones and carrots so to do that back in our code within our nested for loop let's use an if statement so to begin let's cut this line of code into our clipboard this line of code where we are outputting each favorite food so i'll cut that all right and now let's use an if statement so we'll say if the current favorite food that we are outputting is the first item in the array we'll do one thing but otherwise else if it's the second or third favorite food we'll do something else all right so within this first condition of the if statement we can paste our clipboard back in so if it's the first favorite food in the array this works fine but otherwise if it's the second or third favorite food item let's be sure to add in a space the word and and then another space and then output the favorite food all right so let's save this and refresh perfect likes to eat tuna and catnip bones and carrots all right and now we just need to do the same thing for each animal's least favorite foods so back in our javascript after this nested for loop let's add a bit of text to our string so html string and we'll add a space and say and dislikes all right and then we can really just copy and paste this nested for loop and tell it to work with the dislikes array instead of the likes array so let's just copy this to our clipboard and then after this line let's paste in our clipboard let's change this from likes to dislikes change this to dislikes and this to dislikes all right let's save this and refresh meowzie is a cat that likes to eat tuna and catnip and dislikes ham and zucchini beautiful if we click the button a few more times it's working just like we had hoped now before we bring this video to a close i want to try and answer a few of the most common questions you might have right now so question number one is where will i know to look for json urls in the real world right because in the real world there won't be some guy on youtube telling you the exact urls to look for the answer is that every system is different it just depends on the source of your data are you trying to pull data from wordpress are you trying to pull data from a weather forecast service or from a custom php or node api that you built that pulls data from a database you get the idea so there are a million possibilities and each system will generate slightly different urls that you can tweak to return different json so remember in our example how we could tweak this number to be either one two or three to pull in different data well in the real world many of the json urls that you visit will have parameters that you can include in the url to control how many items are returned which items are returned and the order that they are returned in so on and so forth if you're interested in learning more about that you can look up rest apis all right now as of the recording of this video there's a neat website named fill text this website has a bunch of example json endpoint urls that you can experiment with if you feel like practicing ajax okay question number two creating an html string that used our json data was not very enjoyable is there a better way of doing that the answer is absolutely yes there is a better way i only used concatenation and for loops like that in this video because i didn't want to introduce yet another different technology but in the real world i'd recommend a javascript templating solution named handlebars handlebars has been around for a long time it's super popular super useful and it makes creating html out of json data much much simpler i'll try to cover handlebars in a future video alright and the final question question number three what about error handling for our ajax requests right because we don't live in a perfect world and sometimes the browser connection to go out and send or receive data will fail well the good news is that it's very simple to set up error handling so let me jump into the javascript file and we can set up error handling right now so if i scroll up a bit right before this line of code where we send our ajax request let's add a new line and let's say our request dot on error and let's tell it to equal an anonymous function and now this is your chance to say what should happen if the connection just fails outright so maybe the user's internet connection is temporarily down or something like that so you can just log out to the console just as an example you could say connection error obviously in the real world you'd want to do something more useful than just logging out to the console but the general idea is that this is how you handle outright connection failures and then there will be other times where your internet connection is working just fine and you're able to connect to the url or server that you're trying to connect to but for whatever reason the server itself returns an error or the data just doesn't come through correctly and to cover that case we can just add another layer of error handling so within our onload function let's add a new line and let's add an if statement to look for potential errors so we'll say if our request dot status if it is equal to or greater than 200 and that same value our request dot status is also less than 400 this means that we were able to successfully receive the data so if things are successful we just want to run the code that we already had so i'm just going to cut these two lines into these curly brackets but if this isn't the case that means we ran into an error after we connected to this url so then we can just say else and then you would handle the error here so you would do something more useful than this but i'm just going to log out to the console and say we connected to the server but it returned an error all right and that's how you implement basic error handling for your ajax requests that's going to bring this video to a close thank you so much for watching i hope you feel like you learned something and stay tuned for a new video next tuesday thanks bye if you haven't already be sure to check out my brand new get a web developer job mastering the modern workflow course as always there's a link to it in the description
Info
Channel: LearnWebCode
Views: 1,733,756
Rating: undefined out of 5
Keywords: json, ajax, javascript, tutorial
Id: rJesac0_Ftw
Channel Id: undefined
Length: 40min 44sec (2444 seconds)
Published: Wed Oct 26 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.