navigate site menu

Start learning with our library of video tutorials taught by experts. Get started

JavaScript and JSON

JavaScript and JSON

with Ray Villalobos

 


JavaScript Object Notation (JSON) has replaced XML as the core way of sharing data, especially when it comes to JavaScript, since it's so much faster, sleeker, and easier to parse. In this course, dive into working with JSON tools, designing JSON objects, and using different ways to handling JSON data. Author Ray Villalobos also shows how to use AJAX and jQuery to parse your data and feeds, and shows JavaScript and JSON in action in a real-world practical application.
Topics include:
  • What is JSON?
  • Creating simple data
  • Debugging JavaScript objects in the browser
  • Communicating across sites with JSONP
  • Rotating with jQuery Cycle

show more

author
Ray Villalobos
subject
Developer, Web, Programming Languages, Web Development
software
JavaScript , JSON
level
Intermediate
duration
1h 12m
released
Mar 15, 2013

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:00(music playing)
00:04Hey there! This Ray Villalobos, and welcome to JavaScript and JSON.
00:08In this course, I'm going to show you what JavaScript Object Notation, otherwise known
00:12as JSON, is and how it compares and works with JavaScript objects, and how both are used in
00:18building JavaScript applications.
00:20I'll show you how to create, modify, append to, and delete JavaScript and JSON objects.
00:26Then we'll examine how to debug JSON and JavaScript objects with your browser and tools
00:31that are available to anyone online.
00:34We'll also explore how to access and loop through JavaScript objects and arrays.
00:38I'll show you how to use AJAX and jQuery to read external JSON files.
00:42Finally, I'll build a JavaScript carousel that reads an external JSON file into a JavaScript
00:48object and cycles through a series of data.
00:51Let's get started with JavaScript and JSON.
Collapse this transcript
What you should know before watching this course
00:00JavaScript and JSON is not a beginner course, and I'm starting with the assumption that
00:04there are a few things that you already know before taking this course.
00:08You should be familiar with building online projects and know how HTML works.
00:12A really good course to check out is James Williamson's HTML5: Structure, Syntax, and Semantics.
00:17You should also be familiar with basic JavaScript concepts.
00:20If you need help, check out Simon Allardice's JavsScript Essential Training.
00:24When you want to read a JSON File as an external resource, you'll be using a technique called AJAX.
00:29Although you don't need to know AJAX to take this course, you may want to check out what
00:34I consider to be a companion to this course, which is JavaScript and AJAX.
00:38Now, one of the important things to understand about JSON and AJAX is that it is a conversation
00:43that happens between your server and your browser. Because of that, when I'm working
00:47with JSON, trying to run the examples on your hard drive is not going to work.
00:51You'll need to have a server that your pages can talk to.
00:54For that, we've got a couple of options. The simplest one, and what we'll do in this course,
00:58is to work on a live server through FTP.
01:01If you need help understanding FTP and working with the hosted server, check out my course
01:06on Managing a Hosted Web Site.
01:08The other option is to run a local server on your machine.
01:11You can do that with software like MAMP on the Mac or WAMP on a PC.
01:16If you need help with that, check out David Gassner's Installing Apache, MySQL, and PHP course.
01:21You should be comfortable with editing with text editors like BBEdit, Sublime Text, or others.
01:27In this course, I'm going to use an editor called Espresso, but you should use your favorite text editor.
01:32If you're on a Mac, you may want to check out TextWrangler.
01:35It's a free and very capable text editor that is available on the Mac App store.
01:40As you get deeper in web development, you may want to check out its cousin BBEdit, which
01:44is a commercial application that has better web features.
01:47I like another text editor that also works on Macs, PCs, or Linux workstations.
01:53It's called Sublime Text, and although it's not free, it's quite capable and fun to use.
01:57It doesn't really matter which editor you use, as long it's something that you're comfortable with.
02:02JavaScript and JSON is not for beginners, but with just a little bit of background experience,
02:06you should have no problem taking this course.
Collapse this transcript
Using the exercise files
00:00If you're a premium member of the lynda.com online training library, or if you're watching
00:05this tutorial on a DVD-ROM, you have access to the exercise files used throughout this title.
00:10In the Exercise Files folder, you'll find folders for each video in the series.
00:15Inside those folders, you should see a folder containing the files for the current project.
00:20You may also see a working folder and a finish folder.
00:24The working folder has a version of the project when I begin the movie, and the finish folder
00:28has version of the project at the end of the movie.
00:31I'll usually start by copying these files onto my desktop, then opening them up on a text editor.
00:41Because of the nature of JSON and AJAX, occasionally, we'll be working off of files from a server.
00:46I'm using a program like Transmit, an FTP application, to copy these files onto a live server.
00:52If you're a Monthly member or an annual Member of lynda.com, you don't have access to the
00:56exercise files, but you can follow along from scratch with your own assets.
01:00Let's get busy with JavaScript and JSON.
Collapse this transcript
1. Getting Started
What is JSON?
00:00JavaScript Objects and JSON can be a bit confusing, so let's take a minute to discuss what JSON
00:05is, as well as some of the advantages of the format for handling data.
00:09JSON stands for JavaScript Object Notation, and it's a text format that makes it easy
00:14to share data between devices like clients and servers.
00:18JSON owes its origin and it's based on the way JavaScript objects work.
00:22So in effect, it's related to and close to, but not exactly like, JavaScript objects.
00:28Although it's originated with JavaScript, it's available in many different languages,
00:32like C, Ruby, Perl, Python, and PHP.
00:36Because it is smaller and easier to convert into a data structure, it's a great alternative
00:40to other formats like XML.
00:42One of the advantages to using JSON is how easy it is to read.
00:46JSON uses minimal formatting--really just a few special characters in addition to the data.
00:51So here I've created a JSON object with a few key-value pairs.
00:56The keys are on the left-hand side and the value of the keys are on the right hand side.
00:59So for example, the key would be the name, and the value will be my name, Ray Villalobos,
01:05and the position and courses, et cetera, et cetera.
01:08JavaScript can understand this as an object that you can then access.
01:13Another advantage to JSON is that it's super easy to parse.
01:16So for example, you can create an object with this data and then pass it into a JavaScript
01:22object by simply using a JavaScript command called JSON.parse.
01:26You can then do things like access any of the items within the object just by typing
01:31in something like info.name or info.position or info.courses and then specify an item in the array.
01:40So you could say item number 1, and it would output the second item, because arrays are
01:450 index, so this would be building Facebook applications.
01:49If you take a look at the same data expressed in XML notation, which is another very popular
01:56format, you can see that it is a lot larger and more verbose than JSON.
02:00This means that JSON data will take less space and load faster into your web applications.
02:05Plus, parsing an XML object can be complicated and time consuming, whereas JSON is easily
02:12mapped into a JavaScript object and so it takes less time to process.
02:16In recent years, JSON has gotten so popular
02:19that companies like Twitter have even chosen to discontinue support for XML output off the streams.
02:24As you can see on this page, version 1.1 of the Twitter API does not support XML output.
02:31For these and other reasons, JSON is the best format to use when working with data in JavaScript.
02:36If you want to work with JSON in other formats, it has many implementations in popular languages.
02:41If you go to this URL, and scroll down to the bottom of the page, you can see all the
02:46languages that JSON supports.
Collapse this transcript
Understanding objects and JSON
00:00Although the JSON format is derived from and looks very much like JavaScript objects, there
00:05are some differences between the two.
00:07In working with JavaScript applications, we often have to deal with both,
00:11so let's take a look at some of the similarities and differences between JavaScript objects and JSON.
00:16A JSON declaration is a string with names and value pairs.
00:19In JSON, the keys are wrapped in double quotes, not single quotes, so you have to be careful
00:24when defining these.
00:26Make sure you don't try something like this, or that you forget to put the quotes.
00:30This is not valid JSON.
00:33With the quotes it is.
00:35JSON keys can be any valid string.
00:37That means that you can place hyphens, spaces, and even special characters in your key, but
00:42be careful because that makes it harder to access data.
00:46I would stick to just underscores in between spaces.
00:50Do not use the hyphens.
00:51It's better to just use underscores.
00:55JSON values have to be one of six data types: strings, numbers, objects, arrays, Booleans--
01:02which is true or false-- or the special value null.
01:06JavaScript objects, on the other hand, can be any valid JavaScript structure.
01:10So here, we've created a JavaScript object.
01:13It's very close to what the JSON string look like, but you can see some differences.
01:18So for example, we're missing the quotations here.
01:24This is a valid JavaScript name. So where a JSON string could have something like full,
01:29space, name, a JavaScript object has to have something like full_name.
01:36So the quotes on the keys are not going to be necessary on JavaScript objects.
01:42A JavaScript object can also be any data type, including a function, which you can't do with JSON.
01:49Here we assigned the function literal to a key called getName. That would just execute
01:54an alert on a page. It wouldn't do much of anything.
01:56You can put a full function as a JavaScript object value.
02:01Unlike with the JavaScript object, a JSON object needs to be fed as a string into a
02:06variable, and then it has to be parsed into JavaScript.
02:09There's a couple of ways of doing this.
02:11You can use the eval function or the newer JSON.parse function.
02:15Using Eval has some potential security risks, since someone could theoretically include
02:20a script inside some JSON data.
02:23JSON parse in considered to be more secure, but it's less compatible with older browsers.
02:30There is another function called JSON.stringify that does the opposite of parse.
02:35Sometimes it's useful to take an existing JavaScript object and convert it into a string.
02:40It suffers from some of the same compatibility issues as JSON parse.
02:44For that reason, a library like jQuery can be a big help, since it takes care of compatibility
02:50and parsing for you.
02:52For the most part, when you're working within an existing JavaScript file, you'll be working
02:56with JavaScript objects or JSON data that has been parsed into an object.
03:01It's rare to write pure JSON within JavaScript.
03:04JSON will be more useful when reading data from another source.
Collapse this transcript
Creating simple data
00:00JSON & JavaScript objects are really easy to generate,
00:03so let's take a look at some examples of how you would express different types of information in this format.
00:08The most common type of data you would express is key and value pairs.
00:12They are list of keys with their associated values.
00:14Multiple values are separated with commas.
00:17So if we want to add something here--I'll just type Return, I'll put a couple of spaces
00:22and I'll add another key and then I'll place a value on that key and I would need a comma at the end.
00:31Now notice that the last element doesn't need a comma.
00:34You can use whitespace for clarity if you want to, so you can add any number of tabs,
00:39spaces, or a carriage returns and it won't affect the object in any way.
00:45You don't need quotes on numbers, the values true and false--which are the Booleans--or
00:49the special value null.
00:52Once the data has been parsed into a variable, it becomes a JavaScript object.
00:56The easiest way to access elements in JavaScript is to use dot notation.
00:59So you could use info.full_name to access the name of this person.
01:04You can also use the bracket notation, which looks like you're retrieving the value of an array.
01:09This is especially useful if for some reason the keys are not using valid JavaScript names.
01:13So for example, we can use any normal string value right here. So it can have special characters,
01:20even though they're not valid JavaScript names, and then we would have to access them with
01:24the bracket notation.
01:25But it's probably a good idea to keep to valid JavaScript names so we'd use underscores.
01:30We would not use hyphens. Just use underscores and then just alphanumeric values.
01:36Objects can also contain lists which are array-like elements that you can create with brackets.
01:42Here we have a list of courses.
01:44The items are separated with commas, and again, there's no comma at the end of the list.
01:49In this form, you can access these elements with array-like calls using an index number.
01:54Remember that arrays in JavaScript, like in many other languages, are 0 indexed.
01:59So to get to the second element of the array, you would use info.courses, then in brackets, the value 1.
02:05The value of any element can also be an object.
02:08In this form, you can access the element using simpler dot notation.
02:12So to get to the YouTube link, you would type info.links.youtube.
02:17One problem with objects is that you're not guaranteed that the order you type the objects
02:21in is the way they'll be stored by JavaScript in memory.
02:25So if you want to guarantee order, make sure you use arrays instead.
02:28Writing JSON & JavaScript objects can get pretty complicated.
02:32Most of the time JSON will be generated by some application, so we don't have to worry
02:35about that too much, but you really have to be careful about your syntax when creating JavaScript objects.
02:40
Collapse this transcript
Using JavaScript and JSON tools
00:00The format for JSON & JavaScript objects is super simple: just a bunch of commas, semicolons, a
00:07bracket every now and then.
00:08However, it's super easy to make a mistake, so it's very easy to go ahead and forget, like,
00:13to close one of the quotations or not put one of these colons here or forget not to
00:19put a comma on the last element of an object.
00:23So, it's a really good idea to have your JavaScript be checked by different tools, and there's
00:28a lot of stuff online that can help you make your code a little bit better.
00:32So the first one is a tool called JS Hint, and it's an online tool for validating JavaScript
00:38and checking the quality of your code.
00:40So it's not really just for JSON or JavaScript objects;
00:43you can really just paste your code in here and it will check it for any possible errors.
00:47Let me go back to the other page and just grab my JavaScript code, and I'll copy this
00:54and I'll come over here and paste it.
00:57Then we'll hit this Lint button and see what it says.
00:59It says that it has found some problems. So, let's take a look at the problems.
01:03So it's saying that the variable info is defined but never used, and that's really not an error;
01:09it's just that it's super opinionated and because I've just created a variable that
01:13I'm not calling--because that's not a real page like this is not a real quote that I'm
01:18going to use in a real program.
01:19It's just a demo to show you how to access a variable.
01:22It's complaining that I'm actually not using this variable anywhere.
01:25So you can actually modify this tool to not be as picky as it normally is.
01:32So you could maybe click off when a variable is undefined or a variable is defined but not used.
01:37If you check that off and you check this again, it's not going to complain about the code anymore.
01:42So this tool is a little bit picky, but it's really good for checking not just JSON or
01:48JavaScript objects, but just checking your entire JavaScript code.
01:52Now, another tool that you can use is called JSONLint.
01:56This is really a JSON validator.
01:58So it's meant to look at only JSON files, not JavaScript documents.
02:02So if I paste this in here--and I'm going to hit Validate--it's going to find an error
02:07because this is not really JSON. This is actually JavaScript.
02:11So I need to modify this to make sure that it doesn't have a semicolon and it doesn't have the variable.
02:16So I'll hit Validate, and it's telling me that it's a valid JSON.
02:19This would be really cool if you were trying to make sure that you didn't do something
02:23like forget one of these quotes and when you hit Validate, it's going to try to find the
02:27error for you and tell you that there is an error on line 6.
02:30So this is a really good idea to check if you're typing in your own JSON, to make sure
02:35that you've done everything correctly. Also if your JSON is being generated by some sort
02:40of PHP script, then you can pass that along here and it will verify that you've made all
02:46the changes correctly.
02:48Notice that you can also put a URL.
02:49So if you're trying to check the validity of a PHP script that generates JSON, then
02:55you can just paste the URL and it will check that as well.
02:58So by far, my favorite editor is actually something called JSON Editor Online.
03:04You can see it right here. It's super powerful.
03:06It already gives you some sample data so you could see that you could traverse objects
03:09just like you can in the console, and you can make modifications to things.
03:14So you can say here Pete Smith, and you can go from this side of the screen to the other
03:19side of the screen, so you can make the modifications permanently in your JSON document by hitting
03:25this button, or you can modify something here and hit this button and it will transfer to
03:30this view right here.
03:32So you can look at the object just like you would in the console. Plus, it has a lot of
03:38other really cool options.
03:40So another thing that I like is that it lets you just minify your JSON.
03:44It takes care of removing all the white spaces by hitting this button right here.
03:49You can also add the spaces back in, kind of indent everything properly, by hitting this button.
03:54So this is actually an excellent tool for checking out your schema, the structure of
04:00your JSON documents, as you're designing them.
04:03There are also a couple of tools that you can use offline.
04:06You should always have an offline tool, just in case you're on a plane trip or you're not
04:10sure what kind of connectivity or you're visiting your cousin from Topeka who doesn't have
04:14a connection or somebody that has a really slow connection.
04:17So you probably want to find some sort of offline editor.
04:21I like this one for the Mac called Cocoa JSON Editor.
04:24It's a really good tool for looking at the structure of your JSON data, and it's excellent
04:29for working offline.
04:30It's even great for working online, but since I found the JSON Online Editor, I don't really
04:35use it as much as I used to.
04:36Then there is a PC version here called JSONPad.
04:39It's not quite a slick as Cocoa JSON Editor, but it will do if you're on a PC.
04:43There are other tools that you can use to add some JSON functionality to your browsers.
04:48There's a great tool called JSONView, available for Firefox at this URL, and in the Chrome
04:53web store at this URL right here.
04:55So these are both tools that will expand the capabilities of your browser to be able to
05:00see some of the JSON files directly.
05:03So when you pull your JSON document to your browser, it's going to look really nice, and
05:08you're going to be able to visualize it a lot better.
05:10Finally, I really want to show you a tool that I use all the time in my WordPress installations.
05:16It's called the WordPress JSON API.
05:18It hasn't been updated in a few years, but it's still a super-awesome tool.
05:22This is a great tool for pulling your JSON data out of WordPress, such as your articles,
05:28your categories, and your posts, and converting them into JSON data that you can actually
05:33use in other applications.
05:35JSON has gotten very popular as a way of sharing data, and the lists of tools available is quite rich,
05:41so make sure you take the time to explore some of these tools. They'll make working
05:45with JSON and JavaScript objects a lot easier.
Collapse this transcript
2. Working with JavaScript Objects
Debugging JavaScript objects with your browser
00:00The developer tools in a lot of browsers are going to be a really good help when you're
00:04working with JavaScript and JSON.
00:06They understand JavaScript objects and can help you figure out how to access, delete,
00:11or modify your JavaScript variables.
00:13So let's take a look.
00:15I have a document open on the left-hand side, and on the right I have that same document
00:19open in Google Chrome.
00:20To access the console, I'm going to right-click and select Inspect Element.
00:24Now this takes me to the developer tools, but it's going to open them up in the Elements
00:28tab, which just shows you the HTML structure.
00:31We want to get to the console, which is under this triangle right here at the very bottom called Console.
00:37If your window was actually bigger, you will be able to see it all in one line like this.
00:41But my window is really small.
00:42You have to go to this double triangle here and go all the way to the bottom and select Console.
00:47Now, this is just giving you a command prompt, and what you can do here is just type in the
00:51variable that you want to access.
00:53We only have one variable in our script called Info, so we just type that in and hit Enter
00:58and it's going to return the value of that variable.
01:01So in this case, it's saying that this is an object, and you can hit this triangle right
01:06here and take a look at what's inside the object.
01:08Now, you may notice that the order of our element is different than JavaScript's order
01:14of elements as it's displayed in this developer tools.
01:19That's something good to know.
01:20So you could see that in our version of the script which is on the left-hand side, we
01:24have first the full name, then the title, and then the links.
01:27But in the JavaScript version of the object, we have full name, links, and then the title.
01:33It really doesn't matter how a JavaScript organizes the element, except sometimes you
01:37may want to retrieve things in a specific order.
01:40Now, if you open up the links, you can see that each of the links is in an object, and
01:45those are actually going to be in order, because this is stored in as an array, so that's kind
01:49of something important to note: when you want to store something in a specific order, make
01:54sure you do it in an array.
01:56So let me show you how to access things.
01:57All we have to do is type in the variable name and then use dot notation to get one
02:02of the elements, like full_name. And notice that it's auto completing for you, so I can
02:07hit the tab and then Return, and it's going to show you the value of that variable.
02:11So I can access the title by doing the same thing with the title right there: hit Tab
02:16to get to the end, hit Enter. I can access any of the links.
02:20I'll open these up so I can see them.
02:22So I'm going to access this second element which has an index of 0.
02:26To do that, I'm going to come down here and say info.links and then open parenthesis,
02:33put in the index, which in this case will be 1.
02:36That's the second element. First element is 0.
02:39Then type in the object's key. which is Facebook and it's going to return to URL.
02:43I can also modify any variables.
02:45So I can say take info.full_name, and make it equal to something else like say Eric Villalobos,
02:55and now that variable will have that value.
02:57So let's check this by typing that in again and sure enough, it's been changed.
03:02That's only been temporarily changed.
03:04The actual value of the variable in our script is still going to be whatever it used to be.
03:09So if I refresh the document--I'm going to hit the up arrow--that brings in the last command.
03:15Now you can see that it's been reset to whatever it used to be.
03:19So let me take a look at that object again.
03:20I'll say info, open up the object again.
03:23I can also delete any one of the elements, so I can say delete and then in parentheses
03:28info.title and just hit Return.
03:32It returns True, so now, if I type in the object, you can see that that element will be gone.
03:37This is not really doing any permanent damage, but it's a great way to play around with the object.
03:42Make sure you can access the specific variable.
03:45Sometimes with JavaScript and JSON, it's a little bit tough to figure out how to get to a specific element.
03:50Developer tools are a great way to explore your JavaScript and JSON objects.
03:54Make sure they've been formatted properly.
03:56You can also test out how to access specific elements in the JSON or the JavaScript object.
Collapse this transcript
Modifying Array objects in JavaScript
00:00We've already looked at how to access elements in our JavaScript objects using the Developer
00:05tools in Google Chrome.
00:07In this video, I'm going to show you how to access array elements, which are a little bit
00:11different than regular elements.
00:13So I have this document, and I have that document also opened in Google Chrome.
00:19When I access the whole entire JavaScript object, all we do is type in the name and
00:23it gives us the object.
00:24We can open it up and see the other properties in there.
00:28If we want to add a property, all we have to do is just use that same info object and
00:32add something like company, and then I'll put in here lynda.com and hit Enter.
00:37Now, if I query that object again, it will have that added to its list.
00:42To modify something, all I do is info. and then the name of what I want to modify
00:46and change it to something else.
00:48So we've all seen that before.
00:50I showed you how, to delete an element, like say we wanted to delete a company name,
00:55you can use delete method, and then just type in info.company and then delete that.
01:02However, if I try to delete an array element, that's going to actually cause a problem.
01:06So let's take a look at what happens.
01:08So I'm going to open up links, and I want to try to delete an element from the array.
01:16So I'm going to say delete info, and then I will pass it along links, and I'll pass it
01:24along element number two, and I'll hit Enter.
01:28It says it deleted it. So let's take a look at it right now.
01:30So we'll pull up info again, open up the object, and it's saying that there are five elements in the array.
01:37Notice that before it also said that there were five elements in the array.
01:40So let's take a look at these elements and see what's happened to them.
01:44So I only have four elements, but it's saying I have five elements.
01:48Somehow it's taken out array element number two, but it's still thinking that it has five elements.
01:55That's not correct, and that's because you really shouldn't be using the delete function
02:00with array element.
02:01So I'm going to refresh this page. What that will do is it'll clear everything out.
02:05So if I query info again, you're going to see that the object has everything in there: a full name, title.
02:12It's deleted the addition that I made, but that's not a problem, because what we're trying
02:16to do is figure out how to delete elements.
02:18So to delete a node in an array, we have to use a special function called splice.
02:24So, instead of just deleting something, we have to say we want to splice info.links and
02:31then use the splice command, and then we have to tell it which element we want to delete.
02:36So in this case, we'll delete element with an index of 1. And then we have to tell it
02:41how many elements after that I want to delete.
02:44So if I just say 1 comma 1, it will delete element 1 and not element 2.
02:51So it should delete this Facebook link right here.
02:53So let's go ahead and try that. We'll hit Enter.
02:55It shows me the new object.
02:57So I'll query info, open this up.
03:00Now, it's saying, correctly, that there are only four elements in the array.
03:04If we query element 1, it should be the next element, right?
03:09So before, if you looked at it, it was Facebook and number 2 was YouTube and so now, YouTube
03:16has come up properly on that list and it has indexed everything correctly.
03:21So make sure you don't try to delete array objects.
03:24Another thing that you want to do is when you want to insert an array element, what
03:28you want to do is do a push, which is another array function, and you do that like this.
03:33You say something like info.links and then push, and then we'll push in an object just
03:40like any other object.
03:41So I'll do a link for courses, but this is going to be our key, and then our value will be some URLs.
03:54So just like any other object that we would insert in there, we actually have to push it into the array.
03:59So let's take a look now.
04:00It says that it's got five elements once again, and we'll do info just to make sure.
04:07We'll check the links, and the fourth element is that no array.
04:12Now, that's going to allow you to do things sequentially. And you just really have to keep
04:16in mind that objects and arrays behave a little bit differently and that you have to deal
04:20with arrays in a different way than you have to deal with objects.
Collapse this transcript
Looping through JavaScript objects
00:00Once you learn how to add, delete, and modify objects, you'll probably want to be able to
00:04go through the individual elements in order to output them to your application.
00:09To do that, we're going to use the for loop in JavaScript and it has two flavors. Which
00:14when you use depends on the type of data you want to go through.
00:17In this movie, we're going to take a look at how to access object elements with the FOR, IN statement.
00:22We have this object right here called Info, and the Info has a list of links.
00:27The list of links is not defined as an array of objects; it's just defined as an object list.
00:34A list of objects, there's no sequential keys, unlike in an array.
00:37What I'm going to do here is I'm going to add a placeholder for my list of links, so
00:43I'll create an h2 tag right here, and I'll call it links. And then I'm going to create
00:48unordered list and give an id of links.
00:54Now, I'm going to create a variable in our script. So down at the end, after our object,
01:01I want to create a new variable that I'm going to call Output.
01:05This will hold the things that I want to output to my unordered list. And then I'm going to
01:09use the FOR in command. So FOR starts like this and then it uses a key in the array that
01:18you want to try to go through.
01:20In this case, I want to do not just the info array, but the info.links object.
01:25it's targeting the object that has all the links.
01:29Now one thing you want to do when you do FOR IN statements is to check to see that any
01:33other libraries have not added any properties or that you yourself have not added any properties
01:39to an array, because it is possible to add properties to an existing object.
01:44We want to make sure that we don't pollute our list with those elements.
01:49What I'll do is I'll say if info.links has own property, and we'll ask to see if this
01:59links elements has the key that we're asking for. And if it does, we are good to go and
02:08ready to send everything to our output variable. I'm going to create a list item for each element.
02:16Then I'm going to add a link here.
02:18The link is going to point to the key in our object.
02:22Here, because I need to access the links in my links object via the key, I have to use
02:30the array-like notation. Even though this is not an array, it uses these brackets to indicate
02:36that I want to get to the element that has the key that I'm using at the moment.
02:42I'm going to close the end of that anchor tag and then feed the key, which is each one
02:52of these names right here. And then I'm going to go ahead and write down the closing version
02:56of the A tag, which will wrap my key, and close my list item tag right here and close off my output link.
03:10Let me add a couple of comments here.
03:23Now, once I do that, it's time to update the unordered list element that I created up here,
03:29so I'll need to use another variable here called update. And I'm going to make that variable
03:33be the element that has an id of links.
03:40Once I have that element, then I can input the HTML of that element with the output variable that we created.
03:48Let me go ahead and save that, and I'm going to refresh my page, and you'll see all the
03:52links coming up inside my unordered list.
03:55One of the problems with the FOR IN statement is that you cannot guarantee the order of
04:00the elements when they come back. And that's okay if you don't care about the order of
04:03the elements. Like I'm not really sure I care which order of these links are listed in.
04:08After all it is an unordered list that's not supposed to have any inherent order, so it
04:13doesn't really bother me.
04:15If you don't care about the order of the element, you can go ahead and use an object.
04:18Sometimes they're a little bit easier to deal with.
04:21If you do care, it's better that you organize your elements in an array.
04:24It's a little bit harder to write, but we'll take a look at that in the next movie.
Collapse this transcript
Accessing objects in arrays
00:00You can go through each element in an object list in one of two ways, using FOR Loops.
00:05In the last movie, I showed you how to use the FOR IN Loop for working with objects.
00:10One problem with the FOR IN statement is that you can't access arrays in a specific order.
00:15If you want to go through elements sequentially, we need a different version of the FOR statement.
00:20Just like with the previous movie, we're going to start with an info variable, but notice
00:24that it's in a slightly different version.
00:26Instead of being just a list of objects, it's an array of objects.
00:30That's going to be traversed a little bit differently.
00:33We've already placed our h2, which has just the title of links right now, as well as an unordered list.
00:39We'll go ahead and create our variable called output here,
00:43just like we did before, and then we're going to use a FOR statement, but this one is going
00:48to be a little bit different. So FOR statements look like this.
00:52This one goes from a certain variable set to 0 and then to another variable that is set to a count.
00:59Here's where our count is going to be equal to the info.links. And since links is an array,
01:05it's going to be equal to the links length, which is how many items are in the link's object?
01:12I'm going to make this less than or equal to the length of the links array and then
01:18I'm going to increment that everytime I go through this loop by 1.
01:21Now, for each one of those elements, I'm going to have to treat them with the FOR IN statements
01:26as if they were objects.
01:27I'm going to have another set of a FOR IN statements right here, and this is going to
01:31be for the key in info.links with the index from this other FOR loop. So we kind of have
01:41a double loop going.
01:42One of them is going through each array element, and the other one will be going through each object.
01:47We're going to go ahead and put in some comments here, just to not get confused for each object.
01:53And this is for each array element.
01:58Because we're using the FOR IN statement, we want to verify that no other properties
02:02have been added to these objects.
02:03We'll need to use an IF statement and check info.links and the array index.
02:10Make sure that it has the property that we're asking for, which is the key. And then we're
02:16going to actually create our output variable here, so this is going to be our output.
02:22It's going to be plus equal.
02:25List item (li), pretty much like before, except we're going to call things a little bit differently.
02:35Notice that when I'm calling the value of the links elements, I have to use a double array notation.
02:42This first part, this info.links(i), is going to get to the links array, and then the key
02:49is going to let you go through each one of the keys of the elements.
02:52As we're going through each element in the first FOR loop, it's going to be going through
02:57each one of the objects in the array, and then it's going to find the object's key by
03:03using the second array notation here and putting the key from the second loop.
03:23I'm going to add another comment here, so this is going to be the hasOwnProperty Check.
03:31After all these, we're going to update the element that is in our HTML, this unordered list right here.
03:38Now, this technically should be an ordered list, because we're actually caring about
03:43the inherent order of these links.
03:46Notice that I put the YouTube link at the bottom, but these links are essentially alphabetized.
03:50I'll create a variable called update. And it's going to be equal to that element, so getElementById,
04:00and we're targeting the links element that we created up there.Aand then we're going
04:03to modify the HTML of the update variable that is pointing to our links and we're going
04:09to set that equal to output that we generated through that loop right there.
04:13Let's go ahead and save that, and I'll go to my page and I'll refresh, and you see that
04:17the links are coming in, and they're definitely coming in in the right order.
04:21If you're looking to read your objects in any specific order, then you probably want
04:24to fold the objects into an array.
04:27Even though the notation gets a little funky, it's sometimes the best way to organize your data.
04:31
Collapse this transcript
3. JavaScript, JSON, and AJAX
Parsing JSON data with AJAX
00:00JSON and AJAX are really awesome together.
00:03AJAX stands for Asynchronous JavaScript and XML, unless you access documents on a server
00:08without having to reload the page. I use it all the time.
00:12If you go to an application like Facebook, things happen on the same document without
00:16you having to see a different page.
00:19Most of the time, when you're working on your own application, you're not going to access
00:22data from something you type into JavaScript.
00:25You'll be getting data from a file that's usually generated by a database.
00:30You bring that data into JavaScript using AJAX.
00:32In this movie, I'm going to do a quick review of how the code for importing a JSON file
00:36works in JavaScript, but I won't be going over it in detail.
00:40If you want to learn a lot more about JavaScript, make sure you check out the course JavaScript
00:44and AJAX, which I consider a companion to this course.
00:48JavaScript and JSON really have a very symbiotic type of relationship.
00:52Now, because this file uses AJAX, it has to run on an actual server, not on your local hard drive.
00:59AJAX has communication that happens between a server and a client or a browser.
01:04We have to make sure that we have a server in order for it to work.
01:08This file is being brought into my text editor through an FTP client that has access to that server.
01:14If you need to know how to work with FTP clients, make sure you check out my other course, Managing a Hosted Server.
01:21We're starting out with code that's pretty similar to the previous movie, but it has
01:25some important distinctions.
01:27Number one, everything is split out into three different files.
01:31The data.json file has my JSON object.
01:34The index.html file is a lot simpler, just the headline tag and a list of links.
01:39They are ordered links right now. And then I'll call to this other script document.
01:44In that script document, I have a bunch of stuff that belongs to the AJAX part of reading
01:50the file in, as well as the part of the code that you've seen before, where I put everything
01:55in an output variable and I send it to the element.
01:58This is still not working quite yet, because we're missing a line of code, but we'll fix
02:01that in just a minute.
02:03Let me go over to AJAX part.
02:04Now, when you work with AJAX, you create a request that goes to the server, but it is
02:09handled differently in older Microsoft browsers.
02:13This first piece of code checks to see if the browser uses an XMLHttpRequest, also known
02:19as an XHR Request or a Microsoft Active object Request, and it places that into a request variable.
02:26Next, we're going to open the request, asking for a specific file.
02:31Now next, we're going to create an event handler, and that even handler is going to monitor
02:35the status of the request that we're going to make.
02:38We check to see if the request is successful by checking a couple of variables the server
02:43is going to return: the request.status as well as the request.readyState.
02:49If everything checks out, then we can work with our data just like we did before.
02:53Here we're outputting the element to the HTML using the getElementById and update innerHTML.
03:00Right here is where we're actually sending the request.
03:03When JavaScript executes this line of code, it's going to send the request to the server
03:08and when the request is successful, it's going to get to this part, this event right here,
03:14and it's going to execute everything in this middle part.
03:17Let me go ahead and add a little bit of spacing right there.
03:20Let me go ahead and add the single line of code that we need to bring in the data into our object.
03:25It uses a function called JSON.parse, so we'll say variable info. It's the same variable as before.
03:33And then we will say JSON.parse. And what we want to parse is the response text part of
03:40the request that we make, so request. responseText, and we'll format that a little better, we'll
03:49save this, and we'll refresh, and the list comes up just fine.
03:53Let me explain what just happened here.
03:55When the data comes back from the server, it's going to come back as a string in a
04:00special variable called the responseText.
04:03It's essentially a serialized string or a string that converts the JSON object into a normal string.
04:09In order for that string to be converted into a JavaScript object, it has to be parsed.
04:14Parse is just a fancy word for translate.
04:17Once that string gets parsed into the info variable, it's exactly the same as what it
04:22used to be when we created it ourselves before.
04:25Our data will be read into the server and into our ordered list.
04:30Working with AJAX can get really tricky.
04:31If you need a more detailed explanation, make sure you check out the course on JavaScript and AJAX.
04:36
Collapse this transcript
Communicating across sites with JSONP
00:00When working with JSON, sometimes you'll want access to some data that is on a server other
00:05than the one you're currently in, but there's a problem with that.
00:09Some browsers have what's called a same-domain policy.
00:12That means that you can only request data from a site that is in the same place as the
00:17file you're requesting from.
00:18Let me show you how it works.
00:20I'm going to use the Google Chrome browser.
00:22This may not happen to you if you're using Safari, so make sure you try it using Google
00:25Chrome if you want to follow along.
00:27I have a folder with some files, and these files are on my hard drive.
00:32Now, I've placed a JSON document right here on a server, and you can see the opened JSON
00:38document up here on the Google Chrome browser.
00:40Now, what I'm going to do is modify the location of where the document myscript.js is getting
00:48the JSON data from.
00:49Right now, it's assuming that it's on the same folder as this file, so it should be
00:54right here. But I put this on the server, so I'm going to go ahead and put the URL to the server data.
01:01Now, this document is going to read the information from the file that's online, not a file that
01:09is locally on this hard drive.
01:10I'm going to save this, and then I'm going to take this file and put it over here on the server.
01:15Nothing is showing up. Let's take a look at the console and see what's going on.
01:19When I go to the Developer Tools and I switch over to the Console tab, you can see that
01:23we're getting an error, and it's an XMLHttpRequest, cannot load the file name.
01:29The origin is not allowed by Access- Control-Allow-Origin, so that's the problem.
01:33It's trying to reach a file that is somewhere else and it's not in the same domain or in
01:38the same place as the current document.
01:40This script can't get to that JSON file in this browser.
01:45Some browsers will actually let you do that, but this one doesn't, so we need to find a way around that.
01:51To do that, we use a technique called JSONP.
01:53The P in JSONP stands for padding.
01:56I'm going to open up the JSON file from the server, so I'm going to go to my FTP application,
02:01and I'll just select, right-click and say Open, and here's the JSON file.
02:05Now, this one is on my server. This one is not on my local hard drive.
02:09I'm going to modify this file just a little bit, so I'll say dataHandler, and then I'm
02:15going to open a parenthesis right here, and then I'll close the parenthesis right here
02:19and put a semicolon, and I'm going to save this now.
02:22If you take a look at what I just did, it looks suspiciously like a function call.
02:27In JavaScript, when you want to call a function that exists somewhere in your code, you type
02:32in something like some function and then in parenthesis, you usually put in some parameters, right?
02:39This looks exactly like a function call, and it is. And what you're doing is you're telling
02:44this right here, the object, to be the parameter that you're sending to this function call.
02:50That's pretty cool!
02:51That's what JSONP is all about.
02:53We pad our object, and it looks like a function call. And then we can put the object we're
02:58trying to pass as the parameter that gets sent to that function.
03:02Since we're essentially calling a function in our script, it means that we need to modify
03:05our scripts so that it just executes this function.
03:07I'm going to save this, close this out, and then pull up my script.
03:12I'm going to make this window a lot bigger so we can see it better.
03:16We're pretty much going to delete everything before variable output. This is pretty cool!
03:20You're not going to need all the code that actually executes the AJAX request.
03:24We're just going to create the function, because it's going to be called by our JSON file.
03:32Inside the parameter list, we're just going to put a single parameter.
03:35Before, when we were creating this document, we used info as the variable that had the object.
03:40That's what we're going to call here.
03:42When the object comes in from the JSON file, it's going to be fed into this variable, and
03:47then we can use that variable to do whatever we want.
03:49I'll take out this other part right here that actually closes the rest of the AJAX call
03:55and sends the request, because we don't need it anymore, and then I'm going to grab this
03:59and just paste it inside my function.
04:02The reason JSONP works is because scripts don't have a same-domain policy.
04:06If you've ever used any sort of CDN like a content delivery network to load scripts like
04:12jQuery, then you know that you don't need to worry that those scripts are in a separate
04:17location, like you do with AJAX calls. But that means we're going to have to call a JSON
04:22file as a script inside our HTML document.
04:26It's going to look exactly like this.
04:27I'll make a copy of this, paste it right here, and then I'm going to call my JSON script.
04:34Now, I'm calling it after the other script because this script has the function definition
04:45and this has a function call, so I need to make sure that when I call the function, it already exists.
04:50It needs to go after our call to the script.
04:53I'm going to save this, and then we'll come over here and refresh this page.
04:57Sometimes you'll get this error. It's not really an error. It's a warning.
05:01It just depends on how your server is set up. Don't really worry about it.
05:04Notice that if I just refresh the page, it will come right back out.
05:06You can see that my data is loading properly, and my ordered list is getting populated with
05:13the right links and the URLs.
05:15JSONP is a technique that you can use in order to be able to read JSON data from external websites.
05:21What you end up doing is tricking the page into loading our JSON data as a script.
05:26The script calls a function, which is then executed as soon as the data loads.
05:30This is a super-common way of reading data from sites that format information in the JSON format.
05:35
Collapse this transcript
Using jQuery to parse JSON feeds
00:00jQuery is a library that fixes a lot of problems in older browsers.
00:04It also gives you a language for selecting elements in your document object model.
00:09It comes with a few functions for making AJAX calls, including one that is perfect for working with JSON data.
00:15We're starting off with the code from the movie on parsing JSON data with AJAX.
00:20Now, I'm running these files off the server, not a local hard drive.
00:24Whenever you're dealing with AJAX, you have to have some servers that are going to process the calls.
00:30These files aren't on my machine; they're on an FTP server.
00:33We're going to need to add jQuery into our HTML file.
00:37We're going to go to the jQuery website, and I'm going to click on this Download jQuery link.
00:41I'll scroll down right here, and I'll copy this code to use the jQuery CDN.
00:47That's a content delivery network that hosts a lot of common scripts.
00:51I'm going to copy this one. I don't need this other one.
00:54That's just for compatibility with older versions of jQuery.
00:58I'll switch back to my code.
00:59I'll go into my index file, and I'm going to load this before I load myscript.js.
01:05It goes right there, and I'm going to save this.
01:08Now, I'm going to switch to the myscript.js file, and I'm going to remove everything that
01:13has to do with parsing and bringing in the AJAX call from the regular JavaScript, which
01:18is right here. Then I'll delete this other lines right there.
01:22What I need to do next is make sure that the document has finished loading and that jQuery
01:26has loaded properly.
01:28To do that, I'm going to use the (document).ready(function() from jQuery, and let me close it up right here.
01:36I'll put in a comment. Then I'm going to take all this code and paste it right there.
01:42I need to do another function, so this is where I make my AJAX call.
01:46The function is called getJSON, and what I need to do is pass it what I want to get,
01:51so in this case, it would be data.json, because this will be the JSON file in the same folder
01:55as this document, as well as a function literal, so no name.
02:00Into this function I'll receive the variable called info.
02:04When getJSON gets this data right here, it's going to feed it into info, and it's going
02:09to parse it so that it will be ready for me to use in my program.
02:13I'm going to close this off.
02:16I'll put in a comment, getJSON, and all the stuff goes in there as well.
02:22Let me go ahead and save this, and I'll go to my browser and I'll refresh, and I should
02:28get the exact same list, except that now I'm using jQuery.
02:31You see, jQuery is a little bit easier than having to do all that AJAX stuff, and it does
02:36take care of older browsers that maybe don't support the regular JavaScript commands.
02:41Since jQuery is already loaded into a lot of my projects, it's a really a good way to
02:46read in JSON data from files.
Collapse this transcript
4. JavaScript and JSON in Action
Setting up our HTML file
00:00Although this course is about JavaScript and JSON, I've already done a course on JavaScript
00:05and AJAX that's on the online training library.
00:08In this course, in the very last chapter I gave you a good example of how AJAX and JSON can work
00:13together to create a live search application.
00:16If you come in here and you type in a name, you can see that it pulls up a JSON file and
00:22does a live search with the content that you see there.
00:25I wanted to build another application that did something a little bit different, since
00:31there's already a good example of what to do with JavaScript and AJAX in this course.
00:36If you want to check that out, it's a great course that will get you introduced to everything
00:40there is to know about AJAX.
00:42For this course, I want to build an application that is a rotator.
00:45It reads a JSON file from an external source and rotates it using a few libraries.
00:52It's a technique that I use on this website for a local bar camp event in my area.
00:57What I did here is I used this technique to power this rotating list of feature speakers,
01:03as well as the rotating list of sponsors right here, as well as the page footer down here
01:09that has all these icons, plus the list of speakers on the Speakers page.
01:15If you look at this right here, this list of speakers right here uses the exact same
01:19templating code as this list right here.
01:22I'm going to show you how to do that with JavaScript, jQuery, jQuery Cycle, and a library
01:27called mustache.js.
01:28We're going to be using code from this website as well as a library called mustache.js.
01:35It just lets you build templates and lets you take a JSON data file and fit it and roll
01:41it into your current templates.
01:44I'm going to use a rotator that I like to use called jQuery Cycle that allows for the
01:48rotation of different elements, and this is going to be our speakers. Let's get started.
01:55We're going to start with a very basic HTML page right here, and I'm going to just set
01:59up an area for my speakerbox.
02:02I'll do a div with an id of speakerbox. And this is going to have an item inside that's
02:10going to be our carousel, and that's pretty much all of the HTML we're going to need.
02:19We're also going to need to copy the libraries that we're going to be using in this project.
02:24Usually, I go to jQuery and I copy the location of the CDNs from jQuery, but since I need
02:32to do three libraries, there's actually a website called cdn.js.
02:36Cdnjs just lets you get all the libraries you need in one place. And you can do a little
02:41search right here, so we're going to need jQuery.
02:45There's a lot of stuff that uses jQuery. I'm just going to type 1.9.1.
02:50I know that's the latest version of jQuery, so that's going to find the library for me
02:53that I need. So I'm going to copy this and switch back to my application, and I'll add
02:59a script tag, and as the source I'm going to paste that right there and then do the
03:03same for my other libraries.
03:05I'm also going to need jQuery cycle.
03:08I'll type in cycle. And I'm going to copy this link right here, switch over here, create
03:13another script tag, and just paste that in as the URL.
03:17Finally, I'm going to need a library called mustache.js, and the URL for that is right
03:23here. Copy that and do another script tag and paste that in.
03:29That's really all we need to set things up.
03:32We're going to do a lot more in other movies, but this just sets us up with a basic HTML
03:36page, and it links us up to the libraries we need to get this thing going.
03:40One more thing: remember that when you're working with AJAX, you need to work off of a live server.
03:45You can't work with local files.
03:47AJAX is communication that happens between a client and a server, and so all the files
03:52for this project are going to be going into a live server.
03:55You can see the URL right here.
03:57Just remember that if you want to try this on your own, you'll have to use your own server
04:01and FTP the files into a location you can access on the web.
Collapse this transcript
JavaScript templating with mustache.js
00:00Mustache.js is a logicless template library that let's you flow JSON data onto an existing page.
00:07You can have as many templates as you want on a page, so you can take the same JSON data
00:11and display it in different ways.
00:13Using the library couldn't be easier.
00:15You create a template and then bring the JSON file and flow it into an area of your page
00:20using the template as a guide.
00:21Want to know more about mustache? Make sure you check out this website or download the
00:26library directly from github.
00:27I'm going to go my document, and onto my server I have loaded a couple of additional files.
00:34You can see that I have an images folder with some images that I'm going to use later on,
00:40coming from the template as well as a data.json template.
00:44I've got this one open right here.
00:46You can see that it is a speakers object, and the speakers object has an array of element.
00:51You could see it right here.
00:52It's always a good idea to make sure that when you create a JSON document it's formatted
00:56perfectly, or you won't be able to do anything with it.
00:59Let me go ahead and copy this, and I'm going to switch over to the JSON Editor Online.
01:04And what I want to do is paste that right here, then hit this button.
01:09That button will move it over from this side into this side.
01:13Here I can make sure that I take a look at the structure of my objects.
01:16I know this is one object called speakers. It has nine elements and if I expand that,
01:21I can see each element and expand any of the elements to see what the structure would be.
01:26Now, I know that my JSON file is fine because it would've shown me an error if it wasn't
01:31formatted properly, so that's great!
01:33Let's go ahead and go into our index file and first create the template that we're going
01:38to use to display this data.
01:40The template looks a lot like a regular script, so we're going to type in a script tag.
01:44It's not going to have a source, and the type is not going to be text/javascript.
01:49It's going to be text/template.
01:54I need to add an ID so that I can target this later with mustache.js.
01:59Add an ID of speakerstpl for template and now we're ready to create our template.
02:04Our template is going to look at lot like regular HTML.
02:07As a matter of fact, it is going to be HTML, with some additional little placeholders for our data.
02:13First off, I'll start by creating a placeholder for the speakers, and I'll put a pound sign
02:21right here. So this is the first part of the template.
02:24I need to close it, kind of like how I close an HTML element.
02:28Now, where am I getting this from?
02:30This actually comes from my data file, and it's the name of my object.
02:34So what mustache is going to do is it's going to cycle through all the speakers in my object
02:39and apply the template that I'm going to type in here.
02:41I'll create a div with a class of speaker, and I'm going to close that just like I would
02:48any other div. Then I'm going to add an image src.
02:51It is going to be my images folder, and then the name that I call here, shortname, as well as _tn.jpg.
03:02Where am I getting this from?
03:05That is the name of one of these elements called shortname.
03:10Shortname is pretty much the name up here without any special characters, so it has
03:14an underscore instead of a space.
03:17That's how my images are named.
03:18If you open up my images, you'll see that Barot is named with his short name, plus _tn.jpg,
03:25and that's what I'm doing here.
03:28I'll add an Alt tag, and in here I'll pull in the name of this user.
03:39You can probably tell why the library is called mustache.js.
03:43It uses these little curly brackets that look like mustaches on their side, and it uses these
03:48as placeholders to target different JSON elements in your files.
03:52Now, we'll type in an h3.
03:56We'll also need an h4, so I'll do that one as well. And that will have the name and this
04:05other one will have the reknown.
04:07Finally, we'll do a paragraph and that will have the bio.
04:15These are all names of fields in our data.json document. And the template is really nothing
04:22more than just HTML with the placeholders for the template.
04:26Now, we need to create another script.
04:29This one has to go after the libraries load, because this is going to use these libraries
04:33and this is going to be a normal script, so it's not going to refer to an external file.
04:37Here we'll start off by doing that function that executes whenever jQuery loads.
04:46In here, we'll use jQuery's getJSON function.
04:55That's going to load our data file, and when that data file is received, then it's going
05:02to execute a function literal.
05:03It's going to read the contents of data.json into a data object.
05:18We'll create a variable called template.
05:22That variable is going to load the contents of the template that we created up here.
05:26I'm going to use jQuery to target the speakerstpl, which is what I call the template up there,
05:35and read the HTML into this template variable.
05:40Here's the part where I'm actually going to use mustache.js.
05:42I'm going to create an HTML variable, and into that variable I'm going to call the mustache.to_html
05:50function for mustache.js, and feed that the template that I read into the template variable,
05:56as well as the data that we received from the JSON file.
06:00Mustache to HTML will process the data and feed it into the template and then create some HTML.
06:05Once we have that HTML, then we can feed it into a div.
06:11We created the div with an id of carousel to feed that data into, and so we'll modify
06:18its HTML to be the HTML that we received from mustache.js.
06:22So, this id right here is referring to this div id right here.
06:26It's going to feed all that data into that.
06:30If we did everything correctly, I'm going to save this, and I'm going to come into my
06:33page and I'll refresh it, and we should see all the data from our JSON file fall in here.
06:41It's not just the data.
06:42It's actually the data formatted in the template that we chose.
06:45If we select Inspect Element, you can see that this one gets an h3, the sub-headline
06:50gets an h4, and our paragraph is right there as well.
06:55JavaScript templating is one of those techniques that makes your life a lot easier.
06:59Once you know how to flow data into your page using JSON templates, you'll be able to build
07:03websites more efficiently.
07:05
Collapse this transcript
Rotating with jQuery Cycle
00:00We have a list of all of our speakers right now, and they're just in sequential order.
00:05I want to use a library that's going to allow me to create a carousel so that I show
00:09only one of these and they rotate after a period of time.
00:12I'm going to use something called jQuery Cycle.
00:15If you want to learn more about jQuery Cycle, take a look at my series View Source on the
00:20lynda.com online training library.
00:22At the very bottom of the screen, we have, on Week Two, this lesson on creating a photo
00:28rotator with jQuery Cycle.
00:29I'm going to show you how to do it right here though.
00:32jQuery Cycle is a plugin for jQuery that lets you do a lot of different effects as well
00:37as rotate a series of div elements.
00:40We've already loaded the script. It's right over here.
00:43We're going to need to modify our function to use jQuery Cycle to rotate the things that
00:48we've loaded in with the getJSON.
00:50We're going to add a script right here, and it's going to be pretty simple.
00:53What we'll do is we'll go ahead and target the carousel that we created up here, and we'll
01:00load up the cycle function--that's the jQuery Cycle function--and that is going to take
01:05an object as a parameter.
01:08This carousel is this element right here, and in our page we've already loaded all this HTML onto it.
01:15We're going to pass a lot of parameters here.
01:17First, it's going to be the fx, and the fx that we're going to use is called fade.
01:23If you take a look at this page, you can see a list of all the effects you have available
01:28to you. You can click on any one of these to preview what the effect is going to look like.
01:33We'll also pass a pause element here, and we'll set the pause to 1.
01:38Pause is going to stop the rotation if I hover over the main element that has all these items.
01:43Now, if we want to find out what all the different options for jQuery Cycle are, you can go to
01:48this page and you can see all the different options are listed right here with what they
01:53do. So let me try some more.
01:54I'm going to specify a next button, so I'm going to type in next and then put a pound
01:59sign and put a next_btn. That's going to allow people to go ahead and click on the buttons
02:06to navigate forwards and backwards in our list.
02:09Of course, we're going to need a previous button, and I'll have to type in the HTML for that in a second.
02:17Finally, we're going to put in two more things: our speed, which is the speed of the transition--
02:22I'll set that to 500--as well as the timeout, and that is the amount of time between the transitions.
02:28This one doesn't need a comma because it's the last element of the object, and I'll go
02:34ahead and hit Save.
02:36I'll need to come up here and type in the links for my buttons.
02:42They're going to be a href, just a regular link, and I'm going to put that special left
02:52double arrow character. And pretty much the same thing for my next button: it's just going
02:57to have the arrow facing the other way.
03:00Let me go ahead and save this, and I'll come right here and I'll refresh, and you'll see
03:07that only one item is showing. Let me make sure my mouse is away from that element, and it
03:12should rotate after a few seconds.
03:15There's the next one, and I can use these buttons right here to go forwards and backwards through the items.
03:20It doesn't look very good right now, but it does have the functionality that we need to
03:24make this a carousel rotator.
03:26I'll show you how to style it in the next movie.
03:28
Collapse this transcript
Styling our application
00:00Our templating system is working perfectly, and it's even rotating the elements with the
00:04JQuery Cycle plugin, but it could look a lot better.
00:08In this movie, I'm going to show you how to improve the project's looks with CSS.
00:12I've already created a mystyle.css file, and I've opened that up in my text editor, along
00:18with the index.html document.
00:23The mystyle.css file just has a comment.
00:27That comment is going to allow it to work with the live preview feature of my editor.
00:31It's not something you have to type in on your CSS.
00:33I'm going to switch over to the index.html document, and I'm going to go ahead and link these two.
00:40The link relation will be stylesheet, the href will be the location of the CSS file,
00:46and I can take out this type.
00:48I also want to use some custom fonts, so I'm going to head on over to Google Web Fonts
00:53and type in a couple of family names here.
00:55I'm going to use Libre Baskerville.
00:58I'll hit Add to Collection, and I'm also going to load a font called Wendy One.
01:05Add to Collection. Then I'm going to hit the Use button right here and scroll down till
01:09I get the code to add to my project, so I'll copy that back into the index file and load it
01:16up right before my CSS.
01:18I'm going to save this, and I should be done with my index.html file.
01:22I'm going to switch over to mystyle.css and start editing my code.
01:26First, I'll start with the body tag, and I'll set up a background color and set up the font-family
01:36to be that Libre Baskerville, which is what I got from the Google Web Fonts.
01:42I'm going to save this.
01:47I'm going to reload this page and just keep on going.
01:52The speakerbox is going to have a width of 300 pixels and a margin so that it's centered,
02:03and then I'll give it a background color of its own, a little bit of padding, just some
02:13nice rounded edges.
02:14I'm not going to use browser prefixes.
02:16I'm just going to use the standard border- radius, so you might have to add those other ones
02:21if you want to be more compatible.
02:23Occasionally, you'll see me reload the page, and that's because this page is dynamic.
02:27It's loading some scripts, so I want to make sure that the CSS and the JavaScript are matching properly.
02:32I'll set the overflow to hidden so that it hides any text that goes beyond the screen right here.
02:40We'll go on to the headlines.
02:50I'll set the font-weight to be normal, so that it's not bold, because that font that
02:55I'm going to use is pretty bold already, margin 0, so zero out the margins and the padding,
03:02and then on a separate element, I will do the h3 headline by itself.
03:07I'm going to change the font-size, make it pretty big, line-height is going to be .9ems,
03:14so tying up the leading, font-family will be that "Wendy One." Whenever you type fonts
03:21with spaces in them, you have to use these quotations. And I'll change the color.
03:27Let's do the h4 tag now.
03:36Let's change in the color, the weight, and give it a little bit of a margin, and set the
03:50leading or the line-height into 1.2ems.
03:54Next, I'll do the image.
04:01Float that to the right so that it's aligned to the right side of my box.
04:08Give a little bit of more margin on the left- hand side and also give it that little round edge.
04:15The photo right now is pretty big, so I'm going to set the width of the photo to just be 100 pixels.
04:19That will make it nice and tiny and it will fit on the right-hand side of the screen.
04:23Finally, we'll do the paragraph.
04:30I'll change that color of that and change the font-size.
04:37This is looking pretty good.
04:40The buttons could use some help, so I'm going to do some styles for the buttons.
04:52I'll give a little bit of room around the edges, a little bit of padding, and go ahead and
04:56put the background color in so you could see it.
05:04A little border-radius so that they're round-edged.
05:08A little bit of a margin so that they go away from each other and from the top.
05:14I'll change the display to inline-block.
05:21Inline-block allows me to modify the size of the element, even though it might be an inline element.
05:28Now, I need to change the links. Right now, the links are blue and have that underline,
05:34so I'm going to use almost the same code to modify those, just add the anchor tag right
05:40before the Previous and Next Button code.
05:45I'll set the text-decoration to none.
05:48That will get rid of the underlines. And then I can set the background to this more pleasant
05:58pink and set this color to white.
06:02That looks pretty good.
06:05I think I can get rid of this background here and probably move this background over here.
06:11That will be a little smaller code and look pretty good, so let's check it out.
06:17Click on these and it navigates through.
06:24That looks really good!
06:25It's quite an improvement from what we got before.
06:28Our carousel is working really well and now that we've added some CSS, it's looking quite
06:32well as well. Just a little bit of CSS goes a long way to making something look more professional.
Collapse this transcript
Conclusion
Next steps
00:00Thanks for watching JavaScript and JSON.
00:02I really had a lot of fun preparing this course.
00:04I think there are a couple of other things that you should check out in the online training library.
00:08For example, if you haven't already, make sure you look at JavaScript and AJAX.
00:12I consider it to be a companion course to this course, and it introduces you to AJAX
00:17and how to work with AJAX and JQuery.
00:20Now at the very end, in the last chapter, I showed you how to build a Live Search application
00:25that lets you look through a JSON file for a series of listings.
00:29You may also want to check out some of my other courses in the online training library,
00:33including JQuery Mobile Web Applications.
00:36This shows you how to work with different APIs like YouTube, Flickr, Twitter, and also
00:41how to install a JSON feed into your WordPress blog.
00:45Another course that I've made called Building Facebook Applications with HTML and JavaScript
00:50has a whole chapter on JSON that introduces you to JSON and shows you how to build YouTube
00:55and WordPress feeds into a Facebook app.
00:58You may also want to also check out my blog, iviewsource.com.
01:01There are a lot of tips and tricks especially tailored to JavaScript enthusiasts.
01:06Also, I'd like to recommend a few books that you should read. Everyone should read JavaScript:
01:11The Good Parts, by Douglas Crockford.
01:12It's a great introduction to the good parts that made JavaScript awesome.
01:17A new book that just came out that I'm really excited in reading is The Secrets of the JavaScript Ninja.
01:22It's by John Resig, the creator of JQuery.
01:25Another new book that came out recently is Effective JavaScript, by David Herman.
01:29These last two books are great for the more advanced user who's really trying to improve
01:34their JavaScript skills.
Collapse this transcript


Suggested courses to watch next:

jQuery Essential Training (4h 52m)
Joe Marini


EaselJS First Look (1h 28m)
Ray Villalobos


Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked