Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Interacting with JavaScript

From: Working with Data on the Web

Video: Interacting with JavaScript

JSON is pretty popular nowadays, in version 1.1 of their API, Twitter switched to exclusive support for JSON. And all major social media platforms work with the format as well. So, just how do you bring in your own JSON data into your webpage? I'll show you all the steps necessary in this lesson. But before we get to coding, let's take a look at an example JSON data file. On the screen now, is data.json from the Chapter 4, 04, 02 folder of the exercise file.

Interacting with JavaScript

JSON is pretty popular nowadays, in version 1.1 of their API, Twitter switched to exclusive support for JSON. And all major social media platforms work with the format as well. So, just how do you bring in your own JSON data into your webpage? I'll show you all the steps necessary in this lesson. But before we get to coding, let's take a look at an example JSON data file. On the screen now, is data.json from the Chapter 4, 04, 02 folder of the exercise file.

The root JSON object is paintings. Which is a collection of other adjacent objects. Each called painting as you see starting on line three. Each painting in turn has a number of key value pairs, for example on lines five, six, seven, and eight. Now let's turn to index.htm in the same folder. We can use JQuery to read in our data and insert it with any desired HTML and JavaScript code. Best of all, we can do this asynchronously using JQuery's AJAX method.

Let's add our code right after the call that includes JQuery. We'll begin with a script tag. I'll set the type to text JavaScript, and there's our tag pair. Now let's go ahead and set up the document ready function as well. So dollar sign, parenthesis, document. After the parenthesis, .ready another pair of parentheses. And then word function followed by yet another pair of parentheses.

So after that set of parentheses, put in an open and closed curly brace and press Return. Put a closing semicolon after the curly brace and parentheses you see below on line 19 and now we're ready to start adding in our code. Now we'll put in our first real function. This uses the primary AJAX method in JQuery to asynchronously load in our JSON file. The AJAX method takes a number of parameters. So we start that with $.ajax.

Followed by parentheses and curly brace, because we're doing a number of parameters, so type colon and then in quotes, get. Follow that with a comma, after every parameter, except for the last one. We'll need a comma. Next up is URL. This is the file name that we want. And this one is called data.json. Comma at the end. Next up, dataType with a capital T and no surprise, it's JSON.

And then on success, if it loads okay, we'll call the function jsonParser that we're going to write. Okay, let me finish up here with another semi colon and that code looks good to go. I'll scroll down a bit as we add more code here. Now we're going to define our function after the close of the document ready function, put in the keyword function. And the name of our function, jsonParser.

And within the parenthesis, we are passing the argument of JSON. Open a pair of curly braces, and the first thing we're going to do is, because this function would have been called if the JSON file was loaded successfully. We can go ahead and fade out our loading .gif. So dollar sign, parenthesis, single quotes. We'll target the div that holds the loading gif, that's called load.fadeout, all that with a pair of parenthesis and a semicolon.

And next we'll create our JQuery getJSON function. This takes two arguments. The name of the file and the function. So $.getJSON, all uppercase, followed by parenthesis, single quotes, the file we're going to get, data.JSON, function, parenthesis. And what we're going to work with, the data.

After the set of parentheses attached to the word function, put it in a curly brace, and hit Return. Let's go ahead and add our semicolon where necessary after the curly brace and the semicolon there. And I just noticed that I left one off up here. So let's go back and make sure we pick that up. Okay. Now we're ready to work on the heart of our function here, which is the each loop that works its way through the JSON data file. So we'll set up $.each, and open and close paren.

Now the arguments for the each function point to the portion of the JSON file to loop through which are the painting objects. So the way we target that is following down the tree data.paintings.painting. Follow that with a comma. Give our function keyword instead of parenthesis. Now the function has two arguments. One for keys which I'm going to call k and another for the values v.

And after that closing parenthesis, let's put in that familiar curly brace pair and we may as well go ahead and. Put in our semi-colon there after the each function to make sure that we got it all squared away. Now we only really need the values here because we're going to be bringing in the value information and incorporating it into some HTML. So let's set up three different variables to handle those. Var title is going to be equal to v.title. Var image, or img, will be equal to v.image and var price is equal to v.price.

So just so you really understand where we're pulling the data from. Let's just go back to the data.JSON file for a moment. And really what we're looking for are the values that correspond to each of the keys that we see here. So if I look at this, the first one is V title, so the value for our title will be initially boardwalk five. And as it loops through, it will then pick up A Lasting Piece, Surfing High Tide, etc.

Likewise, the image will get the file name here and the price will pull it from the price key. Okay, let's head back to our coding. Next comes the append function which integrates the HTML and data. Let's tiptoe through that because it's a little bit of a piece of work. So, dollar sign parenthesis, single quotes. What are we going to append it to that will be the container and then the function word append followed by a open and close parenthesis.

And a open and close single quotes. Now we are ready to start with our HTML and the first part will be a div to hold the painting, and we'll make sure that has a class of painting. So div, class equals and with your attributes, within the single quotes, you need to use double quotes. So there's our double quote pair, painting and then after that closing double quotes, we'll close off the div tag. Okay that starts off our HTML.

Next, we want to put an image there. So, I'll open an HTML tag, image and then put in our source attribute. Again, we're going to start with a double quote, and Aptana likes to put in pairs of double quotes. So I want to get ride of that one because we'll use that a little bit later, but not quite yet. So now I'll start of my path which is the folder name images followed by a backslash. And now, we're ready to drop in the source that we pull from the JSON data. So we can close off that first bit of the string there with a single quote. Now we add in +.

We don't really need, as we did with XML, to put in a whole long string of JavaScript code to find the XML data. Because we have our variables set up, all we need is the variable image. And then a + to continue our concatenation, single quote and then a double quote because we're finishing up the source attribute. If your code editor like mine puts in a double quote pair, you'll need to get rid of that second one.

Now let's start off with a space and add in our other attributes. The first of which is width, and that's going to be equal to in double quotes 200, followed by space height equal to, in quotes, 225. I have to be vigilant because Aptana loves to put in these double quotes, but it doesn't do it quite every time, because it's matching pairs. So, this time we're okay. Now, we've come to the alt attribute and what I want to do is pull in the title for that old attribute.

So we'll concatenate the variable title, and now we're ready to go back to our HTML. So single quote and a closing double quote followed by the closing of the image tag, forward slash caret. Okay, now we are using a line break, put in a br tab,. and we have another div. This one has a class equal to title, and then close that div tag. And now we're going to put in the title.

So plus, our variable title, plus again, single quote, one more br tag. And now we want to drop in the price, so we're going to put in a dollar sign here and again that ends our little bit of HTML. Pretty minor this time around. And then plus our price. Plus again to finish up the concatenation. And now all we need to do is close off a couple of divs.

So I'll start off with a single quote, slash div, close that div and close another div. Okay JQuery code is done. Let's save the page and try it out. Here's my page and because we don't have the JSON data pulled in yet, the loading gif is running continuously. So let me hit refresh and there's our paintings. Each with the title underneath it and the price. Not too bad right? Of course you can use this same routine to bring in any of your own particular JSON data.

In the next lesson, I'll show you how to take data from an HTML form and store it in a JSON format.

Show transcript

This video is part of

Image for Working with Data on the Web
Working with Data on the Web

25 video lessons · 10091 viewers

Joseph Lowery
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Working with Data on the Web.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

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.

Sign up and receive emails about lynda.com and our online training library:

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

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.