JavaScript and AJAX

JavaScript and AJAX

with Ray Villalobos

 


The ability to read data and communicate information asynchronously is fundamental to modern web applications. In this course, author Ray Villalobos takes a look at integrating AJAX (Asynchronous JavaScript and XML) with JavaScript and jQuery—a combination that makes it easy to work with dynamic data and reduces the number of requests to the server. The course first explains what AJAX is, and shows how to load and reload pages with pure JavaScript, update the DOM, and read and parse data in the XML and JSON formats. Next, learn how to read and write information between the server and the client with AJAX methods in jQuery, and build a dynamic search application that updates search results as you type.
Topics include:
  • What is AJAX?
  • Making requests asynchronous
  • Updating the DOM with getElementById
  • Reading JSON files
  • Working with jQuery and AJAX
  • Sending and searching JSON data
  • Incorporating CSS transitions

show more

author
Ray Villalobos
subject
Developer, Web, Programming Languages, Web Development
software
AJAX , JavaScript
level
Intermediate
duration
1h 12m
released
Jan 18, 2013

Share this course

Ready to join? subscribe


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:03Hey there! This is Ray Villalobos and welcome to JavaScript and AJAX!
00:08In this course I'm going to show you how to use AJAX with JavaScript and jQuery.
00:12I'll start by showing you what AJAX is and how you can use the APIs in
00:16JavaScript to build web applications that update your pages without having to
00:21reload them from a server.
00:22I'll show you how to read and refresh pages with AJAX using pure JavaScript.
00:26Then we'll examine how to update and modify the DOM, the Document Object Model
00:31structure that browsers use to access elements on a page.
00:35We'll also explore reading and parsing data in the XML and JSON format.
00:39Plus I'll show you how to work with the AJAX method in jQuery to read and write
00:43information between the server and the client.
00:46Finally, I'll show you how to build a real AJAX project that lets you search
00:50through a JSON data file with JavaScript, jQuery, and CSS transitions.
00:55So let's get started with JavaScript and AJAX.
Collapse this transcript
What you should know before watching this course
00:00JavaScript and AJAX is not a beginner course, and I'm starting with the
00:03assumption that there's a few things you already know before taking this course.
00:07So you 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:
00:15Structure, Syntax, and Semantics.
00:17You should also be familiar with basic JavaScript concepts.
00:20If you need help with that, check out Simon Allardice's JavaScript
00:23Essential Training.
00:25Now, one of the important things to understand about AJAX is that it is a
00:28conversation that happens between your server and your browser. Because of that,
00:32it means that these examples are not just going to work from your hard drive;
00:35you're going to need to have a server that your browser can talk to.
00:39So for that you've got a couple of options.
00:41The simplest, and what we'll do on this course, is to work on a live server through FTP.
00:45If you need help understanding FTP and working with a hosted server, check out
00:49my course on Managing a Hosted Web Site.
00:52The other option is to run a local server on your machine.
00:55You can do that with software like MAMP on the Mac or WAMP on the PC.
00:59If you need help with that, check out Installing Apache, MySQL, and PHP,
01:04with David Gassner.
01:05Now, you should be familiar and comfortable working with text editors like
01:08BBEdit, Sublime Text, or others.
01:11In this course I'm going to use an editor called Espresso, but you should use
01:15your favorite text editor.
01:16If you're on a Mac, you may want to check out TextWrangler from the Mac App Store.
01:21It has a cousin called BBEdit that is not free, but is a very capable developer tool.
01:26I like another editor that works on Macs, PCs, and Linux workstations
01:31called Sublime Text2.
01:32Although it's not free, it's quite capable and fun to use. And it really doesn't
01:36matter which editor you use, as long as it's something you're comfortable with.
01:40Finally, you're also going to need some sort of FTP application.
01:44I'll be using Transmit from Panic on this course, but if you're on a Mac or a
01:49PC, you may want to check out Cyberduck, which is a free FTP program for Mac and Windows.
01:54So JavaScript and AJAX is not necessarily for beginners, but with just a little
01:58bit of background experience, you should have no problem with 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
00:04watching this tutorial on a DVD-ROM, you have access to the exercise files used
00:08throughout this title.
00:09In the Exercise Files folder you'll find folders for each video in the series.
00:14Inside each of those folders you'll find a version called workingfolder that has
00:18the website when I began the video, and you'll find a finished folder with a
00:23copy of the website when I finished.
00:25So I'll usually begin by opening up the copies of the projects from my server
00:30and open some of the files in my favorite text editor.
00:33If you're a Monthly member or an Annual member of lynda.com, you don't have
00:37access to the exercise files, but you can follow along from scratch with your own assets.
00:42So let's get busy with JavaScript and AJAX.
Collapse this transcript
1. Getting Started
What is AJAX?
00:00So you may be wondering what AJAX is and why you want to learn more about it,
00:04so let's take a look at how you can use AJAX with JavaScript to build dynamic web applications.
00:10Before we look at AJAX, let's talk about how a browser gets information to display a page.
00:14When a browser requests a page from a website, the browser in your machine
00:18is acting as a client.
00:19The website is being delivered through a machine that is serving up the
00:23information, so we call that a server.
00:25When you ask for a page, the client makes a request to the server and the
00:29server returns a page.
00:30Sometimes when you're looking at a page, you may want to ask for some additional
00:33information from the server.
00:35Say for example that your page has thumbnails for a photo album and perhaps the
00:38album has more thumbnails than you can see in the current view.
00:42Without AJAX if you want to see more thumbnails, you'd have to make a
00:45request back to the server and it would send you a whole new page with
00:49additional thumbnails.
00:50That means the server ends up sending a lot of information that you don't really
00:53need all over again.
00:55With AJAX, the server doesn't have to send you the whole page; it just sends
00:59the pieces you need-- in this case new thumbnails.
01:02So how does that work?
01:03AJAX is not a single technology, but a group of technologies working together
01:07to make that happen.
01:09Technically, AJAX stands for Asynchronous JavaScript and XML.
01:12That's quite a mouthful, so let's break that down piece by piece.
01:16Asynchronous means that the client can request new pieces of information from
01:19the server at any time.
01:21It doesn't have to wait for a page to reload.
01:23A new request can be triggered by an event like clicking on a button, hovering
01:26over an image, or whatever.
01:28The J in AJAX stands for JavaScript.
01:30JavaScript is where all this magic takes place.
01:33It handles the events that trigger a new request, makes the requests for new
01:36data to the server, and takes care of updating only the part of the document
01:40that needs to change.
01:41JavaScript talks to the server through a set of programming methods called an
01:45API and uses what's called an XHR or XML HTTP request.
01:50This is where the X in AJAX comes from.
01:52The XHR API lets the browser send and request data from a server.
01:58This can be a bit confusing because a lot of people think of XML as a language
02:02used to describe data that's a lot like HTML.
02:05Sometimes people assume that the X in AJAX means that the data from an AJAX
02:09request has to be in XML, but the data that gets transferred to and from the
02:13server can be in any format, and it's usually either a text file, HTML, or a
02:19JavaScript object, like JSON.
02:21So AJAX is really just a fancy term for a technology that lets you build pages
02:25that update without requiring a page reload.
02:28JavaScript does most of the heavy lifting with AJAX, and it uses the XHR API to
02:32handle the communication between the client and the server.
Collapse this transcript
Using a synchronous XHR request
00:00The first step in working with AJAX is to learn about the API browsers provide
00:05for sending and retrieving information.
00:07The way you access the API is by using a XML HTTP request or XHR object.
00:14So let's take a look.
00:15I'm going to start off with a super-basic page, and it's actually not going to be much of a page;
00:19the only thing this page will do right now is to load a separate script file
00:22that's going to do all of the work.
00:24So I'm going to go ahead and add the script tag right here.
00:26It's going to reference a file called script.js.
00:29And I don't need this type =text/ javascript, so I'll take it out.
00:33And I'm going to save this, and I'll go ahead and create the separate file.
00:36I have Transmit open right here, so I'll right-click and select New File and I'll call it script.js.
00:43I'm also going to need another file called data.txt, so I'll create it by
00:48right-clicking again, selecting New File, and calling this data.txt.
00:51Now, I'm going to open up data.txt.
00:54This file is just going to have the words "Hello World" here.
00:58I'll save it, close this out, and I'm going to open up my script.js file.
01:04I don't really need to do anything with the index.html anymore.
01:07I'll go ahead and open this up. And just to make a little bit easier to work
01:11with, I'll drag it right next to this index tab and so it will doc it at the
01:16same place as this window.
01:18So let's start by creating the simplest of XHR requests.
01:22We'll need to create a new variable for the object that we're creating.
01:30Next, we need to create the request to our XHR object.
01:34The open function of this object is going to require three parameters.
01:37First, the method, which is going to be either GET or POST.
01:43Then the location of the data file.
01:45Since it's in the same folder as this document, it will just be the name of the file.
01:50I should note here that AJAX requests have what's called a same domain policy,
01:54so you cannot request data objects from domains other than the one
01:57you're currently on.
01:59Now, the last parameter we pass is a Boolean that specifies whether we want the
02:04request to be asynchronous or not.
02:06To keep things simple, we're making that false, and that makes a request a
02:10synchronous request.
02:11This makes our browser wait until the request is done before it does anything else,
02:16and this is generally a bad idea, but this is going to make our code simpler for now.
02:21So we've created this request, but it hasn't gone to the server yet.
02:24The send command is going to take care of that.
02:28Now, I'm also going to output the results of the request to the
02:31JavaScript console.
02:32So I'm going to go ahead and save this and take a look at what we get from the server.
02:38So I'll load this page up on the server, and right now the page doesn't do anything.
02:43What I want to do is right-click.
02:45I'm in Chrome right now, so I want to select Inspect Element, and this will take
02:50me to the Developer Tools.
02:51And then I want to hit on this tab that says Console.
02:54So when you click on that tab you'll see that it returned an
02:56XMLHttpRequest object.
02:59And we can open that up and take a look at what's returned from our request to the server.
03:04So one of the important things that we see here is the status of the request.
03:08That property gives us a number, which in this case says 200.
03:13That means the AJAX call was successful.
03:15If any other number was here, like 404 or 500, that would mean the call to the
03:19server was unsuccessful.
03:21So we can modify our code to check for that property.
03:23So I'll save that and then I'll switch over to Chrome, refresh the page, and
03:31you'll see we get the same request.
03:33Now, you can see that text from the file that was loaded in the response and
03:38responseText properties.
03:40The responseText property is what you want to use because it always has just
03:44the text of our response.
03:46So let's go ahead and output that to our document with the writeln command.
03:54So let's save that, and we'll switch back into Chrome, and now we can see the
03:59text Hello World appear in our browser.
04:01So I mentioned before that these requests we're making are synchronous and that
04:05means the server is waiting until the requests are done before it continues.
04:09Right now you really can't see that as a problem, because we're only making a single request.
04:13So I'm going to change the code and make 100 requests to the server to see what would happen.
04:24So I'm going to save this, and I'll switch over to my browser, and I'll reload
04:29the page, and you'll see all the requests being made because I have the console open right now.
04:37You can see that there's nothing appearing in my browser until it finishes
04:41with all the requests.
04:42If you take a look at the Network tab in the Developer Tools in Chrome, you can
04:45actually see that the browser is executing the requests in sequence and that the
04:50page is not even updating until the whole thing is done, and that's not
04:53necessarily a good thing.
04:55So use the XMLhttpRequest object to make calls and request data from your server.
05:00You start by opening a connection and then sending the data.
05:03You can check the status of your requests, as well as access the text returned
05:07by your request and do something with that, like writing it to your page.
Collapse this transcript
Making requests asynchronous
00:00So AJAX requests are supposed to be asynchronous by nature, which means that
00:05they should run in the background independently of other events; otherwise
00:08they would be called synchronous requests and the language would probably be
00:11called SJAX, right?
00:13Really, it's the whole reason AJAX is awesome,
00:15so let's take a look at making asynchronous requests.
00:18So I have a project here open with three files:
00:20a data file with the words Hello World, an HTML file whose sole purpose is to
00:25call a JavaScript document, as well as this JavaScript document, with a single
00:30synchronous request.
00:31I wanted to take a minute to look at this and highlight some of the events that
00:35the request triggered.
00:36So I'm going to switch over to my browser, and I'm going to load up this page,
00:41and then I'm going to right- click and select Inspect Element.
00:45Then I'm going to switch over to the console and take a look at this object
00:49that's returned from my server.
00:50So I'll open up that up, and you'll see that there's a lot of different events right here.
00:54They all start with on. you see onabort, onerror, onload.
00:57There's an event that we're interested in called onreadystatechange.
01:01The browser's AJAX API maintains a property called readyState
01:06that has a number indicating how far along the request has progressed.
01:10If the Value is 0, for example, then the request hasn't been sent yet.
01:14Once the value of that property reaches 4, then the operation of sending and
01:18receiving the requests has been completed.
01:20So what we want to do is modify our code so that it checks the status of this property.
01:25If readyState has the value of 4, then our asynchronous request has been
01:29received and we can do something with the data we get back.
01:32First, before we send our request, we want to change our open method and take out
01:36the false parameter at the end.
01:38We could send a Boolean value of true, but this is the default and so we don't
01:42really need to pass it.
01:44Now we can insert an event handler.
01:45Event handlers will run a function when something happens.
01:49We want to know when the onreadystatechange event changes.
01:53So before we send the request, we'll check that event,
02:02and this will be a function literal, so I'll take out the name.
02:05And then I'm going to grab all this right here and paste it inside this event handler.
02:11I also want to modify our if statement so that it not only checks for the
02:18request status, but also for the readyState value.
02:21So I'll copy this and I'll paste it twice, and then I'll change this one to
02:27say request.readyState.
02:30So this should check to see if the value of request.readyState is equal to 4, and
02:37also if the request.status is 200.
02:42So let me go ahead and save that, and I'll switch over to my browser, and
02:47I'll reload the page.
02:49And you see that we get the same HTML and we get the same result, but the way we
02:54got the result is a little bit different.
02:56So, although it doesn't look any different, this is an honest-to-goodness proper
03:00AJAX request. It sends a request to our server and then waits for that
03:04request to come back at some point; that's called asynchronously.
03:07If you want to learn more about the XHR requests, take a look at this
03:10document from Mozilla.
03:12It's a good resource to see all of the different options available in
03:16XHR requests.
Collapse this transcript
Scripting for backwards compatibility
00:00Although usage of early versions of Internet Explorer have dropped dramatically
00:04in the last few years, it's still important to know how to run AJAX requests
00:07that are compatible with those systems.
00:09And actually, the whole concept behind XHR requests was created by Microsoft and
00:14implemented first in a browser in IE5.
00:17To accomplish this, Microsoft used a technology called ActiveX.
00:21Because ActiveX was not available to other browsers like Safari, Firefox, and
00:25Chrome, they created a different implementation of the API using the
00:29XMLHttpRequest object.
00:32Since ActiveX was seen as a proprietary implementation, the XMLHttpRequest
00:37object became the standard.
00:39So like with a lot of other web technologies, we've ended up with a fragmented
00:43implementation when trying to support older browsers.
00:46Luckily, all we have to do to support these browsers is to check if the browser
00:50API has an XHR object.
00:52So first, I'm going to change this line right here to just create the variable.
00:58Now I'm going to use an if statement.
01:04So if the browser's API has the XMLHttpRequest object, then I'm going to set the
01:09request variable to this new object;
01:14otherwise, we'll check for the ActiveX object.
01:20The rest of our code is not going to change and our AJAX code should execute
01:24in the same manner.
01:24So let's go ahead and save this and I'll switch over to my browser and I'll
01:29just refresh the page.
01:29You see that the page looks exactly the same, but my code is now more compatible
01:34with older browsers.
01:35So even though you might not run into a situation in which you have to
01:37support really old browsers, it's good to know that doing it takes just a few lines of code.
Collapse this transcript
2. Modifying the DOM
Updating the DOM with getElementById
00:00AJAX uses JavaScript to make changes to the current document through
00:03something called the DOM.
00:05This is the Document Object Model, and its job is to keep track of the structure
00:09of our HTML document.
00:10When you work with AJAX it's usually because you want to change something in
00:13your page after it has loaded.
00:15The easiest way to make a change in the DOM is through a JavaScript method
00:19called getElementByID.
00:21So the text editor that I use has a really nice DOM preview feature,
00:25so I'll turn that on right here, and you can see the DOM for our current HTML document.
00:30You can see that there is an HTML tag and inside the HTML tag we have a head
00:33section that has a couple of other elements, as well as a body section with just a script tag.
00:38If we add another element here--let me add a headline--you will see that that
00:45element gets added into the document structure.
00:49If I add a paragraph, that also gets added, and if I create an element like an
00:56emphasis tag inside my paragraph, that gets added as a children of this paragraph object.
01:02Now, if you do add a div with an ID then that ID becomes a way that you can
01:11target that particular element.
01:13So let me go ahead and save this and I'll switch over to my script.js file and
01:17I'll get rid of this console.log method that outputs our content to the console.
01:22Now, since we have an ID, we can easily target it in our JavaScript file.
01:25First we're going to need to create a variable and then find that element
01:28using getElementById.
01:29So I am going to replace this document.writeln command and I'll create a
01:34variable called modify.
01:35I'm going set that variable called modify to be equal to an element in the DOM
01:41with an ID of update.
01:45Now that I have targeted that div in that variable, I can use that variable and
01:49modify the innerHTML, which is the HTML inside the element, to be whatever I want.
01:55In my case, I want to use the request and then look for the responseText. Let's
02:01go ahead and save this, and I'll switch over to my browser, and I'll load up the
02:05page and you could see the document has loaded Hello World into just the ID for update.
02:12So let me go ahead and right-click and Inspect Element.
02:16We could see the div with the ID of update is right here, and I have inserted the
02:20text Hello World from my external document into that div.
02:24So getElementById combined with innerHTML gives you a very quick way to update
02:29any element in your DOM as long as it has an ID.
02:33This is sort of like a laser that lets you target an individual element
02:36very quickly.
Collapse this transcript
Modifying elements with getElementsByTagName
00:00When working with AJAX sometimes you want to access an individual element and
00:04sometimes you want to access groups of elements.
00:06We looked at how to do individual elements with getElementById in the last
00:10video, and in this movie we are going to take a look at accessing groups of
00:14elements with getElementByTagName.
00:17So you could, for example, ask for the third list element in an unordered list.
00:21We are going to need to update our HTML code to do something like that.
00:25So, I'll get rid of this div right here and then I'll add an unordered list
00:29with some elements.
00:30Now I am going to save this and switch over to my script code and modify this
00:39getElementById and make that getelements. Remember, there is an S in there.
00:45ByTagName, the tag that we want to access is the list item tag.
00:52So by doing this, we are going to place an array of elements into the modify variable.
00:56Now that we've got the array, we can access an individual element of that array
01:00by just putting in the index of the element here.
01:03So, if we do modify(2) it will access the third element of the array, because
01:08these are 0 index, so the zero element is actually the first element, element
01:13number 1 is the second element, and element 2 is the third element.
01:17So, if I save this and I switch over to my browser and I refresh the page,
01:22you will see that the third element in my list has been updated with the
01:25content of our data file.
01:27So we grabbed all the list items and we targeted just the third element.
01:32Interestingly enough, if you have more than one list on the page, it'll actually
01:36let you cycle through all the elements as if it were a single array.
01:40Let me show you how that works. Switch back over to my editor.
01:44So, in the index.HTML document I am going to get the original list and then make
01:48another copy right here.
01:50So, let me save that and I'll go over to my script element.
01:53I know that there are six items in the unordered list.
01:56So if I ask for the eighth element, let's take a look at what happens in our browser.
02:01So I'll refresh, and now we have two lists and in the ninth position--that's 6, 7, 8, 9--
02:06it's placed the text of our data file.
02:09There are some more objects down here.
02:11So there is the other bullets.
02:13But it updated the ninth element.
02:15Now there is actually a couple of other ways that you can get to the same place,
02:19so let's go ahead and examine that.
02:19So right here, when I am using modify=document.getElementsByTagName, I am
02:24looking for specifically all the list item elements.
02:27I can actually do multiple copies of this, so I am going to do a
02:30document.getElementsByTagName. And first,
02:35I am going to look for the on order list elements on the page--right now
02:39there's two of them--and I am going to look for the first unordered list
02:43element and inside that element I'll get the ElementsByTagName('li'). That will
02:49target our second list, not the first one. And now I will switch the index here
02:55to be index number 2.
02:56So this is actually doing the same thing in a slightly different way.
03:00First we are getting to the second list by using the index (1) here, and then we
03:05are getting to the elements inside that list that are of type list item and
03:11getting to the third element inside that object.
03:14So, if I save this--and I am going to go back into my page and just refresh--
03:20you'll see that nothing is really changing, but the way that we are getting to
03:23those elements is different.
03:25So what if we wanted to cycle through all the elements in a list?
03:28Say that you wanted to update all the elements in our list items with the
03:32content from the external document. In that case you can use a loop.
03:36So, let's go back into our code.
03:38So we went to, after the modify variable gets instantiated, when I create a for
03:43loop, and that loop is going to go from 0 to the modify variable's length--and
03:50remember that this modify variable is now an array,
03:53so any methods or properties that I would use on an array would be valid here.
03:58And what I wanted to hear is modify, using each index, the innerHTML of each one
04:04of those objects with the response text from the request.
04:10And I also want to make sure that I modify my variable here, because it's only
04:14targeting the second list element, so I want to modify that to just look for
04:18getElementsByTagName, and I'll delete this line right here.
04:21So, what this is going to do is look for all the elements in your page that have
04:26a TagName of list item.
04:28It's going to place all that stuff into the modify variable, and then it's going
04:31to cycle through each modify variable, changing the HTML of each one of them to
04:35the responseText from our request.
04:38So let's save that, switch over to our browser, and we'll refresh, and now you'll
04:42see that it's actually updating every one of these bullet items.
04:45So, getElementsByTagName is really handy for cycling through a series of DOM
04:49elements. Understanding how to handle the array it returns is one of the keys
04:53to modifying your DOM with AJAX.
Collapse this transcript
Parsing XML using AJAX
00:00AJAX was originally designed to read data stored in a format called XML, or
00:05Extensible Markup Language.
00:06It's very much like HTML, but you get to make your own tags.
00:10So let's take a look at an example of what it takes like to read data in this format.
00:13We have a new file in our folder called data.xml.
00:17It's a file with some data in the XML format.
00:20If you know a little HTML this should be super easy to read.
00:23You can open an XML file with some browsers to see the structure a little bit better.
00:28So we have a speakers object, and inside the speaker objects we have a
00:33series of speaker objects.
00:35Each one of the speaker objects has different parts to it, so for example we
00:39have the <name> tag, the <shortname> tag--which is the same as the <name> tag
00:43but without spaces or special characters--as well as the <reknown> tag and a <bio>
00:48that has some information about the speaker.
00:51Reading this into JavaScript is super simple. As a matter of fact, the XHR object
00:56comes with a special attribute called responseXML.
00:59It's sort of like the responseText property, except that it converts the data
01:03into an object that you can manipulate through JavaScript.
01:05So, before we do anything else, let's go back into our HTML file and change this
01:09so we're back to a div with an id of update.
01:12So, I am going to go ahead and save this, and we are going to switch to the
01:18script.js file. And now we need to change the request so that it doesn't request
01:23the data.txt document, but instead uses our XML document.
01:27I am also going to remove the lines of code that are looping through all of my elements.
01:32So now that we are linking to the XML document instead of the text document let's just
01:36take a look at the responseXML property of our request.
01:44So let me save that and switch over to my browser, and let me hit the Back
01:48button to go back into my file, and then I'll refresh this.
01:51So, let's go into our console and take a look at what we get back.
01:54So, you see that what we get back is essentially a document with some data inside it
02:00that's pretty much like what we saw in the XML file.
02:03The XML object is really easy to go through.
02:06We can use the getElementsByTagName with an HTML or an XML document.
02:11So if we wanted to get to, say, the name of the second user, you can do something like this.
02:19So let me go ahead and save that, and then I'll switch over to my browser and
02:24we will hit Refresh.
02:25So what we get back is the entire <name> tag of that XML node.
02:29So every element inside an XML structure is considered a node. Elements inside
02:35other elements, including the text inside an element, is also considered a node.
02:39So, to get to the text of this node we could use this.
02:45So let me save that and switch back to my browser and hit Refresh.
02:49You can see that we are getting the name. It still has quotes which is not exactly
02:52correct, but at least we are not getting the tag anymore.
02:55So there is actually a shortcut for the first element in any array, and
02:58it's called firstChild.
02:59So if we do this, it's the same as writing child nodes zero. Refresh,
03:04we get the same results. Back over here,
03:06so if you look at what we get, it's the value in quotes, and it's not exactly the
03:10text of the node. To get that we would have to use the nodeValue property like this.
03:15So I am going to save that, switch over to my browser, refresh, and now we get
03:20just the text without the quotes.
03:22So, let's see what it will take to make a list of our speakers.
03:25We'll have to cycle through the XML file using a for loop.
03:28When the request is ready we'll create a variable that looks for the
03:32elements with a tag of name.
03:33Then we are going to create an output variable with an unordered list.
03:45Inside this, we are going to create a loop. And here we'll go ahead and add the
03:51value of each result as list items.
03:57Now we will send the results of all this to our div with a value of update.
04:04So let me save this and preview this in my browser, and you can see the list of all our names.
04:12So although you can read data in any format besides XML, the AJAX API was
04:16designed with an easy-to-use responseXML property that makes it a trivial matter
04:21to read and parse XML files.
Collapse this transcript
Reading JSON files
00:00Although AJAX was designed to work with files in the XML format, it will read
00:04the contents of any text file.
00:06So the data can really be in any format; the trick is to know how to parse or
00:10translate the data into objects that JavaScript can manipulate. An obvious
00:14choice is to use the file in the JSON format.
00:16JASON stands for JavaScript Object Notation, and is a way to structure data so
00:20that it can be easily converted to a JavaScript object.
00:23If you want to learn more about JSON, make sure you check out my course on
00:26Building Facebook Applications with HTML and JavaScript.
00:29There is a section called Adding JSON Data Feeds, and it has a good introduction
00:33to the JSON language.
00:35So, let's go back and take a look at what a JSON document looks like.
00:38If you watch the movie on parsing XML using AJAX, this is the same data, but in
00:43a slightly different format.
00:44The good news is that parsing data is super simple--sort of; some browsers
00:48support a parse command,
00:49so let's go into the JavaScript file and replace the code for processing or XML file.
00:54So, I'm going to modify this open command to open the JSON document.
00:59Now I'm going to take out the rest of this code right here, and I'll create a
01:04variable called items and set it to the JSON object and use the parse command
01:10with the responseText of the request. Then I'll output this to the console so we can look at it.
01:19So let me save this and I'll switch back to a browser, refresh our page, And if
01:25you have the console openm remember that you could just right-click on this page
01:29and select Inspect Element if you are using Google Chrome like me. And I can see
01:33the series of objects that this returns.
01:35If I open that up, I can see each individual object and inside each object, I can
01:40see different name and value pairs.
01:42So this is a little different from what we would see with XML.
01:45It's essentially an array of objects and each object has a label and the
01:49data from our file.
01:50So here's the bad news: JSON parse is not available in some older browsers.
01:55So, if you go to this website, you could see that it's available in most
01:58modern browsers, but a lot of the older versions of IE do not support the parse command.
02:03So your options are to use EVAL--but that has some security issues--write your own
02:07parser, or use an existing library.
02:10jQuery for example, takes care of this very well.
02:13Let's go back to our code.
02:14So we'll modify our code so that it outputs a list of speakers.
02:18We'll start by creating the output variable, just like we did with XML, and then in here
02:26we'll loop through the valleys of the objects.
02:28To do that I am going to use the for in statement.
02:35Finally, we'll target the update element with the results of our output variable.
02:43So let's save this and switch back to our browser, refresh the page, and you can
02:49see that the list appears.
02:50So working with JSON files is pretty easy with the parse command.
02:53However, it might not be available in all browser versions. So for ultimate
02:57compatibility, I recommend that you use a library like jQuery.
Collapse this transcript
Using event-driven AJAX
00:00You can use AJAX to update items on a page as a result of some type of event.
00:04Events in JavaScript can happen as a result of a user action, like a click or a
00:09mouse over an element, and some are triggered by other events, like when
00:14something has finished loading or when a key is released.
00:17You can use JavaScript to capture the event when it happens and trigger a
00:21series of commands.
00:22So first, we're going to clean up our HTML a little bit.
00:24We'll take out this AJAX page h1.
00:26It's not really doing very much.
00:29So let me go ahead and save that. And then I'm going to take my script and wrap
00:33it inside a function.
00:34So right now this script is executing whenever it gets to it in the index.html
00:40file, which is at the very end.
00:41So this page loads and then the script runs right here, so all this is executing
00:46right then. So what we'll do is prevent that from happening, by putting
00:49everything inside a function.
00:54So we'll grab all those code and we'll paste it right there.
00:56Let me go ahead and indent that a little bit.
01:02And now if I save this and I take a look at my page, you'll notice that nothing
01:07is happening because that function is not being called.
01:10So one of the ways that we can call a function is by creating a trigger. So I'm
01:14going to add a button here and I'll call this button Load,
01:17and I'm going to do an onclick event here, and it looks just like an
01:20attribute. And then I'll put LoadAJAX, which will call the function we created in JavaScript.
01:25So let me save that and I'll switch over to the browser, refresh the page.
01:30We see the Load button, and when we click on it, it should load the text from our file.
01:34Of course there's more events that you can use.
01:37For example, you can see if somebody has placed the mouse over the button.
01:40So we can do that with a different kind of event here;
01:43sometimes these are called event handlers.
01:45So we can do an onmouseover, and I'll save that, refresh our page.
01:51Now when I go over this button, it loads the text.
01:54So mouse over that button and there's the text.
01:57So something interesting about events is that not all elements on a page can
02:01trigger the same types of events.
02:03So for example, there's an element called onload, so you might be tempted to
02:07say something like this: whenever this button finishes loading, then execute the function.
02:12So let me save that and see what happens. When I refresh the page, this is not
02:16loading, and it really doesn't matter what we do here.
02:18That's because the onload event doesn't make sense for buttons;
02:22it really only makes sense for a page or a body tag.
02:26So it's an attribute that can only go in the body tag.
02:29So let me save that and come over here.
02:32I'll refresh the page, and now you can see that it's kind of doing what it did before.
02:37As soon as the page loads, or as soon as the body of the page has finished
02:40loading--and it's going to load the text from our file.
02:44That's just one thing to keep in mind, not all elements can trigger any type of event.
02:47There's actually a ton of events.
02:48This is a really good place to find out about all the different events:
02:52when they happen and what triggers them.
02:54So events can be triggered either as attributes, like we have done right here,
02:58and they can also be triggered directly through JavaScript.
03:00So I'm going to take out the onload handler here and I'm going to save this.
03:05If I want to trigger this with JavaScript, I'm going to add an ID to my button
03:08so I can easily get to it.
03:11So I'm going to save this and I'll switch over to the JavaScript file, and what
03:14I'm going to do is create a variable that gets to that button using
03:21document.getElementById, and the id that I want is the loadbutton that we created in HTML.
03:27So that puts the button in the mybutton variable,
03:30and then what I can do is check for a click.
03:33So I can say mybutton.onclick= and then I can execute the function called loadAJAX.
03:41So I'll save that. And notice the different notation here.
03:43I don't need the parentheses in here.
03:45So I'll save that, come over here, refresh, Load button, and now when I click
03:49on the button, it loads my text.
03:52So there's a different way to write this, and it doesn't really matter which way
03:55you do it, but you'll see it in both ways on the web.
03:59So one of the things that you can do to shorten this a little bit is actually
04:02create the function as a function literal.
04:04So I can get rid of all this right here and just say =function and then it will
04:11just execute the function as soon as that mouse is clicked.
04:14That's okay if this is the only button that's going to load the list of names for us.
04:18If you wanted to use a function that was more generic, you might want to keep it the other way.
04:22So let me save this and over here refresh, and we click and there's our text.
04:27So events are pretty easy to work with.
04:29They can be triggered either through an attribute in the HTML or through an
04:33event handler in JavaScript.
Collapse this transcript
3. jQuery AJAX
Understanding and installing jQuery
00:00jQuery is a framework that fixes compatibility issues that happen with
00:03JavaScript in older browsers.
00:05The library also gives you a lot of additional tools for working with the DOM.
00:09One of my favorite features of the framework is how easy it makes it to work with AJAX.
00:14So let's go ahead and take a look at some of the options you have for installing jQuery.
00:18So there's two ways you can include jQuery into your projects.
00:21You can download a copy or use it from a CDN.
00:24A CDN is a content delivery network.
00:27You can see links to those if you click on the Download tab right here and then
00:31look over here to the left.
00:32Those are links to the most popular CDN libraries that have jQuery.
00:36You can also try cdnjs.com;
00:39that has copies of a lot of libraries, including jQuery.
00:43So the advantage of using a CDN is that if a browser has loaded your library
00:48from a CDN when you visited some other website, it may already be cached in your
00:53browser when it comes to your site, so your page will load a lot faster.
00:56The disadvantage is that CDNs will only work while you have a live connection to the Internet.
01:01If you're working with a local copy or maybe flying around on an airplane or
01:05coding where your connection is spotty, then the CDN is not going to load at all
01:09and none of your JavaScript will work.
01:11So you load them both into your code in pretty much the same way.
01:13So let's go ahead and go to the front of the jQuery website and click on this Download link.
01:19Now, before you do that, see that there's two options here.
01:22You have the option of downloading a Production version or a
01:25Development version.
01:26Now, the Development version has a copy of all the code with comments that's
01:30super easy to read, but it's obviously a lot bigger.
01:33Whereas the Production is minified and Gzipped, which means that it's
01:36compressed, it has no comments, a lot of the variable names have been changed
01:40so that they're smaller, and it's really pretty impossible to read.
01:43You should use the Development version if you're going to be editing something
01:46about the jQuery JavaScript code; otherwise, just use the Production version, and
01:50that's what I'm going to do.
01:52So I'll click on Download jQuery.
01:53Sometimes you see this kind of code right here, which is essentially the
01:56JavaScript code for jQuery.
01:57I told you the Production version was hard to read, and I wasn't kidding.
02:01Now, to save this I'm going to go to the File menu--
02:03I'm using Safari right now--and I'm going to select Save As. And here I'm just
02:08going to rename this jquery.js and I'll just save it on the Desktop.
02:14I want to make sure that from this Format menu, I choose Page Source.
02:19Make sure it's not in Web Archive.
02:20So I'll select that, hit Save, and now that saves it into our desktop, so I'm
02:25going to switch there.
02:28And what I need to do now is copy this into my server,
02:33so I'll copy that just by dragging it.
02:35I'm using Transmit as my FTP program, so there it is.
02:38It's already on my server.
02:39And now what I want to do is select the files that I need and open them up in my editor.
02:44So I've got all these files opened up in my editor.
02:50There's the jquery.js library.
02:52I really don't need to see it, so I'm just going to close it up.
02:55What I need to do to insert it is go to my index.html file and then load it up
02:59just like I would any other script.
03:01I want to make sure that I load it up before my script.js, because that's where
03:04I'm going to be putting my regular JavaScript and I want to make sure that the
03:07library is there before my other scripts load.
03:11So I'll do a script tag, and as the source I'll just type in jquery.js.
03:17I don't need this part.
03:19Now, the only difference between this and loading it from a CDN is that if you
03:23were to load this from a content delivery network, you'd want to get the URL of
03:27the library and just copy that from here and paste it into your script tag.
03:33But I'm not going to do that because I'm just using a local copy.
03:36So save it and now jQuery will load into my application, and it's ready for me to use.
03:42Loading up jQuery is normally done using one of the CDNs when you're in
03:45production, but keep in mind that if you're going to be offline and developing,
03:49then downloading a copy is a super-smart idea.
03:51One more thing: you should always load jQuery before your regular JS file.
03:55That way all the power of the framework is going to be available when you
03:58write your scripts.
Collapse this transcript
Working with jQuery and AJAX
00:00jQuery is a great library and one of its mottos is that you can write less
00:04and do more, and one of the places where you can really see that is when working with AJAX.
00:08So let's take a look at how we can use AJAX with jQuery.
00:11jQuery provides several methods for working with AJAX calls, and you can see all
00:16them in this page right here.
00:19So for the most part, you end up working with one or two of these.
00:22So let's go ahead and load some content onto our page.
00:25Our HTML file is a simpler version of what we had in the last chapter, just
00:30a div with an id of update, and we're loading the jQuery as well as our script file.
00:35The script document right now is empty, and our data file just has the words Hello World.
00:39So I'm going to switch over to my script and I'm going to type in some jQuery right here.
00:44So I'm going to target the update id element and then load into it our data.txt document.
00:53So let me save that and switch over to my browser, refresh my document, and you
00:58can see the text Hello World.
01:00So there's actually a lot going on in that very simple line of jQuery code.
01:04jQuery is taking care of a lot of problems with backwards compatibility in older
01:08browsers, and it also creates and sends the XHR request.
01:12Not only that, jQuery gives you new ways of selecting elements.
01:16Here we're selecting something in the DOM-- in this case a div with an id of update.
01:20If you watched the chapter on modifying the DOM, you know that JavaScript has
01:24two main methods for getting to elements:
01:26getElementById and getElementsByTagName.
01:29You may have been wondering why I didn't talk about getElementsByClassName, and
01:33that's because although there's some support for this method in a lot of modern
01:37browsers, the support is not yet universal, and even if it were, working with
01:41complex selectors is much easier to do with jQuery.
01:44Let's modify our code so that we can use a class name instead of an ID.
01:49So I'm just going to change this ID right here to class, and all I have to do in
01:54jQuery is just modify this pound sign right here to select the class of update.
01:58I'm going to save that, switch over to my browser, refresh, and the text still comes up.
02:04So, classes are supposed to refer to elements that occur multiple times in the DOM.
02:08Let's go ahead and go to the HTML file and just copy this update element a few times.
02:14So I'm going to save this and I'll go back to my browser and I'll hit refresh,
02:20and now you can see that it's loading multiple times.
02:23So the load event is just going to take all our content with the same class and
02:27replace it with the text from our file.
02:29So jQuery is not only going to improve what you can do with JavaScript, but
02:32it goes beyond that and gives you totally new selectors with which to access the data.
02:37So check this out.
02:38I'm going to go into my JavaScript file. So what I'm going to do is change this
02:41so that I only select the first of all the update classes.
02:45So I'm going to save that and switch over to my browser and I'm going to refresh.
02:49And you can't really see what's going on here. So I'm going to over to the Elements.
02:52I have the Developer tools open.
02:55If you don't have that open, just right-click and select Inspect Element.
02:58I'm using Google Chrome as my browser.
03:00But take a look at the code right here.
03:02It's still showing the other classes, but it's only changing the first one.
03:06And that's pretty cool.
03:07So let's go back and try another one.
03:11We can actually tell jQuery to just load up the even classes.
03:15And I'll save that, come over here, refresh, and if you take a look at our code,
03:19we've got three up here, but it only did every other class right here--and
03:24that's really, really powerful,
03:25easy way to do something like zebra striping on tables.
03:28Using jQuery is going to take care of a lot of the grunt work necessary to work with AJAX.
03:33It also gives you some powerful new ways to select DOM elements.
03:36I think it's good to understand the XHR object and how JavaScript handles things.
03:41When it comes down to taking care of business, it's hard to argue with the
03:44convenience that JQuery provides.
03:46If you want to know more by jQuery, make sure you take a look at Joe Marini's
03:49excellent course, jQuery Essential Training.
Collapse this transcript
Reading data with jQuery
00:00In the last movie we used jQuery's load method to load some text from
00:04an external source.
00:05If you're looking to load structured data, jQuery has a method called getJSON.
00:09As the name implies, it's designed to load data in the JSON format.
00:13So once again, I'm beginning with a simplified version of our HTML file.
00:17It's pretty much just a div with an ID of update, and then they call to jQuery,
00:21as well as our script file.
00:23Our script file right now is empty, and we're going to need a file called data.json.
00:27It has the data that we need to load into our document.
00:31So in our script file we'll start off by calling the getJSON method.
00:38We'll pass it along the file name that we want to load and then we'll create a function.
00:43This would be a function literal so it will have no name.
00:47And we want to pass along the data that we get from the getJSON command
00:51into this function.
00:52So let's go ahead and output the data to our console so we can take a look at it.
00:59So let me save this, and I'll switch back to our browser.
01:02I'll hit the Refresh key.
01:04And I want to make sure I switch over to the Console tag.
01:08And that should give you a list or an array of objects.
01:12And if we open that up, we can see that each one of those objects has name and
01:16value pairs with different parameters here.
01:18And this is essentially how a JSON object looks to your browser.
01:22So I want to output a list of some of the names of our speakers, so let's go
01:24ahead and prepare an unordered list right here.
01:28I'll take out this console.log command and I'll create a variable called output.
01:32This is going to have an ordered list here. And then at the end of this list, I
01:39need to close the ul tag.
01:40So instead of using the for-in JavaScript loop, I'm going to use jQuery's
01:48built-in Each statement.
01:49I'm going to pass along the data and then a function literal.
01:56And that function literal is going to have a couple of variables:
01:59one of them called key and the other one called value.
02:04So this is similar to using a for- in statement, but a little better
02:07because jQuery always tries to do a great job of dealing with browser and platform issues.
02:12When you have a choice, it's always better to use the built-in functions.
02:15So in here I'm going to modify my output variable, and I'll output a list
02:23item, and I'm going to use the value variable and pass along the name
02:32and close out my list item.
02:33So where am I getting this name from?
02:36That's actually from the list of objects and the name of value pairs that I get right here.
02:41So the name is right here for each one of these objects.
02:44So I can call any one of those by just calling this value and then adding .name to it.
02:49So to update the HTML, we need to use the jQuery HTML method.
02:57So I want to target our update div and then change the HTML to have the output
03:03that we created above.
03:05So let me save that and I'll switch over to my browser and refresh, and you can
03:09see all of the names coming up from the file.
03:12So jQuery also provides additional methods to manage your data.
03:15Let's say, for example, that instead of just replacing all the HTML inside a
03:19tag, we wanted to append some HTML to the end of our list.
03:23So let's modify our HTML so that we already have something in this div id update.
03:29So I'll just create an h1 tag right here and I'll call it Speakers. I'll close it up.
03:34So if we were to run this right now, you would see the Speakers in the text and
03:39it would disappear and get replaced with this list.
03:41But instead of just replacing the HTML, we can actually do stuff like append the
03:46HTML, just with an append method right here.
03:49So I'm going to save that and I'll switch over to my browser.
03:52And now instead of deleting what was already there, I just placed
03:55something after it.
03:56Of course if there is append, you would think there is a prepend, and of course there is.
04:04So now that puts the text before the content of what was already in there.
04:08So with jQuery reading in a JSON file is pretty simple. A lot of times the added
04:12functionality of methods like append, prepend, and others makes it a better way
04:17to work with JavaScript.
Collapse this transcript
4. AJAX in Action
Preparing a live search AJAX app
00:00So it's time get busy with a real project in AJAX.
00:03I'm going to show you how to build a live search application, and this is what
00:06the application looks like when it's done.
00:09This application lets you type in some text in this input field and shows you
00:13only the records in the JSON document that match the search.
00:16It's dynamic, in that it updates as you're typing them.
00:21We're going to use some of what we have learned about AJAX so far and use some
00:24of jQuery's power to handle the heavy lifting.
00:26So let me go over the documents I'm going to start with.
00:29First off, I've cleared up the JavaScript file so that it has nothing in it.
00:32I want to begin with a clean slate.
00:34I'm going to get rid of some of the files I no longer need that are still in my
00:38server like this data.xml and this data.txt file.
00:42So I'm hitting Command+Delete, I'm in Transmit, and then hit this Delete
00:46button, gets rid of them. Eventually I'll need to add a style sheet to my HTML file, so I'll go ahead and
00:50right-click in Transmit and select New File and type in mystyle.css.
00:56You may have also noticed that I uploaded a folder full of images, and these are
01:00just photos of the different speakers.
01:04So the HTML that I'm starting with is pretty simple.
01:07I've changed the title to Live Search, and I just have div with an ID of update
01:11and a link to the jQuery and the script.js documents.
01:15So the first thing I'm going to need is to add a section for my search area.
01:19So I'll create a div, the id will be searcharea, and in here I'll type in an input field.
01:28I'll make it of type search. In some browsers you may see the edges have rounded corners.
01:32Now, it doesn't really matters what I type for name because this is not going to be
01:37part of a normal form, but I do have to add an ID value here because that's what
01:41we're going to target JavaScript.
01:43I don't need a value, so I'll take that out. I am going to add a placeholder.
01:47That's an HTML 5 feature that let's you put in something that the reader can see before they type anything.
01:52So if I switch over here and I clear my search, you can see that it says name or
01:55info right there, so that's what I'm going to type here: name or info.
01:59So this going to need a label. A label is just the text that goes with the input
02:03field, and it has an advantage of making the label clickable to the input field.
02:09So this needs to match the id, so I'll do an id of search here, and my label is
02:13just going to say livesearch.
02:15That means that when I am here, if I click on the word livesearch, because that's
02:21the label, it will activate my field.
02:23That is something really useful for mobile devices.
02:25And I'll add a little paragraph here to just describe what the user is supposed
02:31to do. So, let me save that.
02:37Finally, I need to add a link to my style sheet.
02:41And the style is called mystyle.css.
02:47I don't need a type here. Let me save that.
02:50One thing I like to do is to just put a simple rule in the style sheet to make
02:55sure that it's linking properly to the HTML file.
02:58So I'll add a body selector here, background, and just give it a background color.
03:06So let me save this and I'll switch back to my browser.
03:09I need to go to a slightly different URL here. And everything looks like
03:14it's working great.
03:15So we've done a little bit of work here, and this is pretty much it for our HTML file
03:19and our folder structure.
03:20It's a really simple page, so now we can move on to start scripting the document.
Collapse this transcript
Sending JSON data to the page
00:00In the last movie we set up the HTML document for our Live Search application.
00:04In this movie we'll go ahead and start creating our JavaScript file.
00:07We're going to use JavaScript and jQuery.
00:10So, let's take a look at the HTML from the previous movie.
00:13It's just pretty simple:
00:14a single form element with an ID of search plus an additional div that has an ID of Update.
00:19Both of those are going to be pretty important in our script, so let's dig in.
00:22I will switch over to my script file, and I'll start off by doing some things
00:27we've done in previous movies.
00:28First, I'll just read the JSON data and output it into our update div.
00:32So I will start off by using getJSON.
00:35I will get the data file, and the data will be fed into a function literal.
00:46This will read the JSON file and then, as a callback, will run an anonymous
00:50function and pass along the data that we have.
00:53One trick that I've learned from debugging JavaScript for years is to try to
00:56test things out as soon as I write them.
00:58So let's just go ahead and send this data to the console.
01:01I am going to save this and I will switch over to my browser. I will refresh,
01:08and then I'll do a right-click--
01:10I am in Google Chrome right now--and select Inspect Element.
01:13Then go over to the console.
01:15Make sure that we have this object right here showing, which we do.
01:18That means that my jQuery is working properly.
01:20It's getting the element from the file, and it's retrieving it and putting
01:24it into this console. So that's great.
01:26Now let's go ahead and output that data into our div.
01:29Let me take out the console.log here. And I will create a variable called output,
01:33and I will start by feeding it just an unordered list tag.
01:36I will add a class so that I can target it with CSS.
01:44I will close that out.
01:52Now we can use the each statement to output the list items.
01:55This is a function literal, and we'll get the key and value variables set up.
02:07Now we need to start outputting just the names like before, but this time I'm
02:10going to put the beginning and closing li tags on their own line.
02:13That just makes it easier to add other elements.
02:15So I am going to add an h2 tag here and output the name from the value variable
02:27that gets created from this each statement right here.
02:33Now all I need to do is output the HTML into my update div.
02:42So let me save that and I will switch back over to my browser and hit
02:46the Refresh button.
02:47You can see one of the names come up here. Let me make that a little bigger.
02:51All the names are now coming up from the JSON document.
02:54Now we can add the rest of the elements we want from the JSON file.
02:58Let's go ahead and add the image tag.
03:04In the image tag I am going to use the field called shortname.
03:07It just has a simplified version of the persons' names.
03:10So if they have three names, or this Jonathan G. Ferrar II, I just call them
03:15Jonathan Ferrar and then put an underscore in between them, and those relate to
03:19the file names of the images that I have for each speaker.
03:23In my script file, I can just use that, making sure that I target the images
03:27folder, then the slash, that shortname, and then _tn, for thumbnail, .jpg.
03:34For the alt, I will just make it the name of the speaker.
03:37For the biography, I am going to copy this one and just stick it in a paragraph
03:42tag, and just call the val.bio.
03:48So let's take a look at this in the browser.
03:51We'll refresh, and we could see the name of the author, the photo, and the bio come up.
03:57Perfect! So, so far, our page is simply displaying the information from our JSON document.
04:02It's not very different from what we've done in past videos.
04:05In the next movie, I'll show you how we can capture events from the search field
04:08and create a search engine for our JSON file.
Collapse this transcript
Searching JSON data
00:00Previously, we managed to set up our application and load some content from a JSON document.
00:05In this video I am going to show you how to handle events from the input
00:08field, as well as how to use those events to drive some search functionality
00:11into our application.
00:13So we can check for an event happening when users interact with a specific
00:16element on the page.
00:17This technique is called binding the event to the element, and jQuery makes that easy.
00:22If you're using straight JavaScript, this is a good list of all the
00:25events available in HTML.
00:27If you're using jQuery, then you need to check this page for a list of the
00:31jQuery version of the same events.
00:33So we have events like change(), dblclick(), error(), et cetera, et cetera.
00:37The one that we're interested in is the keyup() event,
00:40an event that happens when somebody releases the key on their keyboard.
00:43So let me come over here.
00:45I am going to target the input field with the ID of search.
00:49Then I am going to bind a keyup element--
00:51this is the jQuery version--and I'll execute a function literal.
00:55That function literal will have everything that we did previously.
00:59So all the stuff will go right there.
01:01Let me indent that a little bit, and I am going to save this.
01:04I will switch over to my page, and I am going to reload the page. Nothing will be showing.
01:08As soon as I click right here and start typing something in, then my JSON document will load.
01:14This is not really searching anything, but it prevents the display of the JSON
01:19data until I type something in the search box.
01:22So now it's time to narrow down our results.
01:25To do that we're going to need to be able to get the text the user is typing,
01:29so we're going to create a variable for that.
01:35Here, once again we target the div with an ID of search, and we're getting the
01:39value that is in that field.
01:41So let me go ahead and output that to the console.
01:43Let me refresh the page and as I type something in here, I should be able to
01:53click onto my console.
01:54So you can see the text that appears when I type something in the input field
01:59down here in the console. That's working pretty well.
02:01In order to do as search, we're going to use a JavaScript function called search.
02:06Search takes a string and looks for another piece of text inside that original string.
02:10If it finds it, it returns its position.
02:13The string method can search for either some text inside another string or use
02:17a regular expression.
02:18If you search for some text, it will do a case-sensitive search, which is not what we want.
02:23So when somebody types a lowercase b, it wouldn't find Barot, because that user
02:27has a name that starts with a capital B. And that's not good.
02:30Regular expressions are sort of like search on steroids that let you do
02:34case-insensitive and more powerful searches.
02:36I am going to need just a very simple regular expression,
02:39so let me do that right here.
02:41I'll get rid of this console.log, and I'll call this my expression or myExp, and
02:47that's going to be a new regular expression.
02:51That's going to take in our search field, and it's going to use the
02:55case-insensitive search if I type i in quotes right here.
02:58Now that we've got these two variables, we can use the search method like this.
03:01I am going to wrap this around the list of output items right here, and I will
03:06type in if the value of name from our data file and then execute a search
03:12passing it a regular expression. The one that we created is called myExp.
03:17If that is not equal to -1, it means that it did find that text in the data.
03:25So if it does, then I can output all the stuff.
03:33So let me go ahead and save this, and I'll go back into my application and I
03:37will reload. I will start typing something in here, and you'll see that it is
03:44producing the search result.
03:46So let me close this out so you could see it a little better.
03:51There's all my search results right now.
03:53It's pretty much everyone.
03:54So if I type in a name, like I will type Ferrar here, it finds that second field.
03:59I will just do that a little more. It is dynamic,
04:01so it's narrowing things down as I type in more and more text.
04:04That's pretty good,
04:05but right now it's only finding things in the name field.
04:09So I also want to check for the Bio field.
04:12I can just take this, and I'll add another set of parentheses here and an or symbol.
04:23Paste that other copy of it and change this to check the bio field.
04:32So this says look for the regular expressions in the name or in the bio field.
04:37I will save that, come over here, we'll refresh, and we'll try something like
04:43media, because I know some of these people have the keyword media, or maybe
04:48something like art, and now that's working perfectly.
04:50So our Live Search functionality is working great, but it doesn't look very hot,
04:54so in the next movie I am going to add a little bit of styling.
Collapse this transcript
Styling an application
00:00So far, we've managed to build a nice live search feature that uses AJAX to
00:04search through a JSON data file, but the UI could look a little bit better.
00:08So in this video I'm going to show you how to style this application with CSS.
00:12Now, I've got the set up in Espresso and this little comment right here
00:15essentially ties my live preview with this window. So as I make a change right
00:19here, it will update automatically.
00:21If you don't have Espresso, you don't really need to type that in, but it's just
00:25the way that I have things set up, so that as I type the CSS, you're going to be
00:28able to see the changes on the right-hand side. So let's get started with some basic CSS.
00:33So first, I'm going to start working on the searcharea, and I'm going to go
00:38ahead and center that by setting the margin equal to 0 and auto.
00:44I'll text-align this to the center so that the text inside will also be
00:49centered, and I'll set up a background color here, and I'll set up a padding of
00:5710 pixels. Plus I'll set up the width to be 30% of the page.
01:01That way this is going to be responsive and kind of grow with this page.
01:05I'm going to add a bit of a border-radius here, and that will just make my edges round,
01:10so I'll use -webkit-border- radius and I'll do 10 pixels.
01:14That will take care of Safari and Chrome. And then I'll do -moz-border-radius
01:1710 pixels for Firefox, and then I'll just use the regular rule, which is just
01:25border-radius of 10 pixels.
01:29I want to make the border just be on the top, left, and right of this box, so
01:33I'll modify this -webkit-border- radius to have some different values.
01:38So let's style the label.
01:44We're giving it some font attributes here.
01:46I'll go ahead and make the text- transform be uppercase, so that it displays
01:50that text as uppercase always, and I'll add a little bit of padding at the
01:54bottom of 5 pixels,
01:56just a little bit of breathing room. And I'll set the color to a little bit of a red tint.
02:06So now let me do the same thing with the paragraph.
02:08I'll grab this and I'll just copy it here, and instead of label, I'm going to
02:12target the paragraph.
02:14The margin is going to be nothing.
02:15Gets rid of all the spacing on the top and bottom.
02:17And then I'll do a line-height of 1 em and a padding at the bottom of 5 pixels.
02:26Again, just putting in a little more breathing room this time.
02:29This looks probably a little bit better when it's wider.
02:34So now, let's modify the input field.
02:37Once again, searcharea. And I'm going to set the width to be 80% of the size of
02:45the window, again, making it responsive. And I'll text-align this to the center.
02:51So now this little box is actually going to grow as I change the size of the window.
02:58Excellent! So now we need to change the style for the content, which is under the update id.
03:04So we'll start with some basic code to change that.
03:07I'll do a font-family, and I'm going to use Georgia and as a backup, Times new Roman.
03:19And I'll set the width of that to be 70% of the browser window, and I'm going to
03:24center it horizontally, so margin will be 0 and auto.
03:28And I want to put a border on the top, and I'll make that border dotted.
03:35And my border color is going to be CCC.
03:38That's just a little gray line at the top of the update div.
03:42So let's go ahead and change the unordered list.
03:45Right now my lists have bullets in them, so I'll do update unordered list.
03:51I'll get rid of the bullets with list-style none, and I'm going to change the
03:56margin and the padding to 0.
03:58That gets rid of a little bit of space that happens with unordered lists.
04:02So now I'll do update ul li, and I'll set the width of this to be 100% of the
04:10container. And I'll do a little bit of padding so that it has a little bit of
04:16breathing room to each side.
04:19I'll set up a background color here.
04:21You can actually see the padding better with the background color.
04:23So there's without padding, and there's with padding.
04:26I'll do a little bit of padding at the bottom, 10 pixels.
04:31You can't really see it, but that just gives you a little more breathing room
04:35between some of the list items.
04:38And I'm going to set the height, because they're a little big, to be 110 pixels.
04:42And now that looks kind of weird,
04:44so I need to make sure that I do the overflow element here and I set it to be hidden.
04:50That hides everything that's bigger than 110 pixels.
04:53And we'll do also a little border at the bottom, so that we kind of visually
05:04tell the user that there is going to be more information underneath this little
05:09border that we placed.
05:10All right, so when users hover over the list item elements and when I have a
05:16style that kind of expands what I've done, so my background is going to change,
05:20the background color.
05:25I'll set the height to 250 pixels.
05:27That's going to show more of the content behind.
05:31So if somebody hovers over one of these elements, it kind of expands this to
05:35be bigger right now.
05:36It's still sort of funky, but it will work really well when we have the rest of the code in.
05:41Let's do the update h2 tags.
05:46And I'll do margin.
05:47I'll just clear out the margin and padding and then set up a font-size, a little
05:54bit of padding at the top and bottom, and we'll change the font here.
06:01Now, we'll change the color, kind of a little bit of a red, sort of maybe a
06:14coral color, and we'll add a border and a little bit of the margin to give the
06:28border a little bit of room right here.
06:30So now I'm going to do the image.
06:35I'll float the image to the left.
06:36That way the text will show to the right of the image.
06:40And I'm going to set up the width of the image to just be 80 pixels so that
06:44it's not so gargantuan.
06:45I'll add a little bit of margin to the right, 10 pixels, just to give it a
06:50little bit of breathing room from the photo, and I'm going to make the photos
06:54have a round edge, so I'm going to type in -webkit-border-radius, 10 pixels,
07:04and I'll do the same thing for Mozilla browsers, and for just the regular version CSS.
07:12So let me save that, and that's looking pretty cool, and it's mostly
07:16accomplishing what we need here.
07:20You can see that this looks really good, especially when it expands.
07:23So our application is looking pretty good, and this would probably be good
07:26enough for most projects.
07:27However, in the next movie, I'm going to show you how to use some CSS3 animations
07:31to improve this app.
Collapse this transcript
Adding CSS3 animations
00:00Our application is looking pretty good and it works well, but I think we could
00:04spice it up with some CSS3 animations. Som this won't necessarily work in some
00:08older browsers, but I think it adds a little bit of pizzazz to our
00:11application and makes it degrade nicely in older browsers.
00:15So at the very bottom of our CSS, we're going to add some animation keyframes.
00:19We'll need to add them with different browser prefixes.
00:22The prefixes are pretty similar, so we'll just do one prefix and copy and paste
00:26and then modify it for the other prefixes.
00:28So I'll start with webkit, because I'm in a WebKit browser.
00:31The way this works is you defined a set of keyframes and then you give them a
00:35name, inside this keyframes keyword.
00:39So what we want to do here is start our animation at the beginning position, or
00:43the 0% position, with the opacity of the object being at 30%.
00:48And then at the end of our animation, which is 100% of the keyframe, our opacity
00:53will be set up to 1.0, which is full opacity.
00:57So what this will do is it will just fade in the elements that I am targeting
01:01with this animation.
01:02So I have the webkit prefix going.
01:04Now, all I need to do is copy that and paste some other copies and modify the
01:09prefix for other browsers.
01:16So now that we have these keyframes, we can call this animation sequence
01:20within our list item.
01:21So I'm going to scroll up a little bit and find the place where I do the list
01:26items and add some code right here that call in our animation.
01:29So, for that, I'll do webkit- animation and then I'll call in my animation
01:34(my anim) and make it run for one second, and I'll need to do that with other prefixes.
01:43So let me go ahead and save that, and I'll refresh this page, and you can see
01:49that these elements right here are fading in as I'm typing in some of these search fields.
01:59So, another thing that I want to do is make this expanding animation be
02:03little more fluid, so for that, I'm going to use something called transitions.
02:07And transitions work sort of like animations, except that they happen when an element changes.
02:13So I have got a hover event here, and I want to set a transition that
02:17happens when the element,
02:19it's in its normal state, and when somebody hovers over the element.
02:23Now, I need to just put the transition here in the original version of the
02:27element, so I'll do webkit and not animation, but transition.
02:30I only want to animate the height element of the transition, so I'll need to tell
02:36it how long I want that to last-- that'll be 0.3 seconds--and then an easing-in and
02:41easing-out function.
02:42I'll just to use ease-out,
02:44so that makes it slow at the end of that transition. And let me delete this and
02:51just paste this a few times and add the other browser prefixes here. So I'll save that.
03:00Let me refresh this, and I'll type in this name here.
03:04You can see that when I type in a search that results in multiple fields,
03:10you can see that when I roll over some of these elements my transitions, are a lot smoother.
03:14If you want to learn more about transitions and transforms, make sure you check
03:18out this course from Joseph Lowery in the library.
Collapse this transcript
Conclusion
Next steps
00:00So thanks for watching JavaScript and AJAX.
00:03We've have got a lot of really good content in the online training library
00:06related to JavaScript, so here are some courses you should check out.
00:09Definitely start with Simon Allardice and JavaScript Essential Training.
00:12Even for experienced developers, you may find some really good tips and tricks,
00:17and some good introductions to some of the concepts that you need to know to do
00:21some more advanced courses.
00:22Now I tend to cover a lot of JavaScript-related courses, so here's a list of
00:26some of the other things I have on the library, like, for example, Building
00:30Facebook Applications with HTML and JavaScript, which has a good introduction
00:34to JSON data feeds.
00:36You should all check out my course on jQuery Mobile Web Applications.
00:40It also has some additional information about hooking up to different kinds of
00:44APIs through JavaScript.
00:46You may also want to check out my blog, where I write about a lot of JavaScript-
00:49related topics, including templating with JavaScript, Bootstrap, and other
00:54libraries that I think are pretty cool.
00:56Another article that I suggest you read is this one from Douglas Crockford on JavaScript:
01:01The World's Most Misunderstood Programming Language.
01:04So, thank you again for watching, and I hope you have a great time programming the web.
Collapse this transcript


Suggested courses to watch next:

Node.js First Look (2h 10m)
Joseph LeBlanc


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 98,466 instructional videos.

start free trial 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 1,893 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.


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