New terms from treehouse – AJAX Basics Part 2 – jQuery and AJAX and AJAX and APIs

jQuery is great in that it makes me feel less terrible about my JS skills. It also makes working with AJAX extremely simple and quick. Many people exclusively use it for their AJAXin’.

We are apparently able to replace all the code we had to write out for the first example with just these lines:

Screen Shot 2014-10-13 at 12.44.55 PM

The #ajax selects the div on the page with the id ajax, and the .load method is shorthand for requesting a bit of html and then loading that into the page. It is one of many helpful AJAX functions in jQuery. We can then hide the button with the .hide() method.

Screen Shot 2014-10-13 at 12.47.51 PM

jQuery’s AJAX Shorthand Methods

They made these for the most common kinds of AJAX requests, listed here. .get() method is a way to send a GET request to your server. This actually doesn’t use a selector, we can just use it with the dollar sign jQuery symbol. It takes a few arguments. The first is the url, the one you’re making the request to. The second is optional, and is data you send to the web server, which is added to the url as a query string. You can actually use JS objects here instead of just a string.

For example, if you want this:

Screen Shot 2014-10-21 at 1.06.45 PM

You could actually do this:

Screen Shot 2014-10-21 at 1.07.08 PM

The third argument is the callback function, which is the code that runs after the response from the server. The difference with jQuery is you don’t need to check the XHR ready status or for any errors. It’s only run when the AJAX request is complete and successful. You write it like this, and the response argument in the function is the same as the responseText property of the XHR object from the last stage.

Screen Shot 2014-10-21 at 1.10.31 PM

You can also insert the info directly in instead of using variables.

Screen Shot 2014-10-21 at 1.12.25 PM

Let’s see how we can replace the load() method with the get() one.

Screen Shot 2014-10-21 at 1.14.07 PM

Note that the load method is easier and less code. It’s just nice to have different ways to do things.

Office project revisited

Here we’ll rewrite this project in jQuery rather than JS. jQuery has a AJAX helper function called getJSON() that not only performs the necessary AJAX requests, but also parses the returned JSON file. It works like the get() method seen before.

We’ll start with $(document).ready, which is a jQuery function that waits for all of the HTML to load before running the code. This is required only when including the link to your js files in the head of the file, before the body of the html.

Screen Shot 2014-10-21 at 1.27.53 PM

Note: he added the comment to say what the closing brackets are for, which helps clarify things when writing jQuery.

We then add in the getJSON method, which accepts the same arguments as the get() method. The data argument is optional, and we won’t use it here. Once again, we can create a variable or insert the value or function in directly. Note: the response here is expecting to receive JSON, if the server sends back anything else, like plain text or XML, the getJSON method will fail. We can then start adding to the anonymous callback function. We’ll set statusHTML to an opening ul tag with the class bulleted.

Screen Shot 2014-10-21 at 1.34.58 PM

Remember, the JSON file we’re linking to is just an array of objects containing the name and their in/out status. Before, we used a loop. In $, we can use the .each function, which works the same way.

Screen Shot 2014-10-21 at 1.36.28 PM

For the array argument, you enter the index number for the value you want, like the i in a for loop.

Screen Shot 2014-10-21 at 1.38.08 PM\

Screen Shot 2014-10-21 at 1.39.19 PM

So in our example, data is the array we’re referring to. Then for each object in the array, value has two properties, each with a value, for name and inoffice.

Screen Shot 2014-10-21 at 1.40.36 PM

Let’s add that to our code. We’ll name the second argument in the anon function employee, since it’s basically a list of objects containing info on employees. The rest of the code is basically the same as the last one where we add list items with a certain class depending on the value of employee.inoffice. Make sure to add the closing ul tag outside of the loop, otherwise it will add one every time. We then add the html to the page using the .html() method, using our statusHTML variable as our argument.

Screen Shot 2014-10-21 at 1.52.09 PM

Posting Data with jQuery

The get() method is good for small things, like an email address, but for larger things, like a blog post, use post(). It’s for data meant to be stored in a database. It takes 3 arguments again, the url you’re sending to, the data you want to send, and the callback function you want to run after it’s sent and you get the response. For the data, you can use a JS object like for get(), but more commonly you’ll want to use data from a form.

Screen Shot 2014-10-22 at 11.52.54 AM

jQuery’s serialize() method can take a form’s worth of fields, encode them and prepare the data to be sent to the server. Below, we show how to use it:

Screen Shot 2014-10-22 at 11.58.04 AM

First, we use the $(document).ready because they put this code in the head section. Then they select the form element, and put a .submit() event handler so this triggers when the form is submitted. Then, they prevented the default action of the form so the submit button wouldn’t work as it normally would. Then, they created an attribute for where we’re posting to, url, and the data of the form, formData. For form data we use .serialize(), which goes through all the form fields and encodes them for us. Finally, we do a post() and finish up by having it change the html of the #signup element once it’s complete.

The AJAX method

get() and post() are actually built from a more complex and robust method, the $.ajax() method. It takes a url for the request, like the others, but then also a JS object containing key value pairs that set various other options of the request. They are listed out in the documentation above. Let’s redo the last post example with this one. Basically you plug everything you need into the object.

Screen Shot 2014-10-22 at 12.08.13 PM

So why use this? For flexibility. The get(), post() etc shorthand methods are convenient but limited in comparison. For example, you can set a timeout, to wait a certain amount of time to hear back from the server. After which you can quit the AJAX request, and do something else. Or if you need user authentication, you can set that up to pass along with the request. Still, the shorthand methods are useful for most requests.

Handling Errors

jQuery’s AJAX functions fail silently, meaning that your callback function won’t work in that case. Sometimes that’s okay, but sometimes you want to let your users know that’s a problem.

Let’s say you’re building a chat app. You submit a message with a form, and it gets sent to the server via AJAX. Then, the recipient receives it via AJAX as well.  But what if there’s an issue where it doesn’t send? You should notify the user.

The .fail() method’s purpose is to run a function when an AJAX request fails. It can be used for all of jQuery’s JAAX methods except the .load() method. Since jQuery supports chaining, where you tack on one method to another, you can simply add fail() to the end of another.

Screen Shot 2014-10-22 at 12.24.16 PM

It takes a single argument, a callback function that runs if the request fails. jQuery passes several arguments to it, but the only really useful one is the first, a jQuery XHR object (jqXHR), which is an enhanced version of a regular XML Http object we learned about earlier and includes extra helpful properties, like info about the error via the .status property. Here we show that using the alert function.

Screen Shot 2014-10-22 at 12.29.04 PMScreen Shot 2014-10-22 at 12.29.15 PM

If you instead use the .statusText property it will explain it via text and you can give that to the user.

Screen Shot 2014-10-22 at 12.31.04 PMScreen Shot 2014-10-22 at 12.32.44 PM

But, if you just want to print the error to the page there’s an even easier way, just create a variable with a string explaining it, and add that to the html. Not sure why he wrote the variable and then added to it though, you could just do it all in the line where you declared it.

Screen Shot 2014-10-22 at 12.33.55 PMScreen Shot 2014-10-22 at 12.34.58 PM

Remember, .fail doesn’t work for the $.load method, nor for remote AJAX requests that use JSONp, which are requests to a different web server.


What is an API?

All sites let you access them using a web server, but some also provide a method from accessing content from another webserver via a server-side language like php or ruby. An API, or, Application Programming Interface is the method that let’s you connect your site to a third part web service, like youtube or flickr. It defines what you can get from a web server, and how you get it. Each site that has one has it’s own unique one. Some have JS API’s that you can access via AJAX, without the need of a server-side language.

Flickr’s API

Most API’s will make you apply for an API key, where you let them know who you are and what you want to use their API for. It acts sort of like a password, when you connect to their web server you need to send along your API key. It let’s them know who is making the request, and limits access to the service and content accordingly. This let’s them revoke the key also if needed, if you’re doing something bad or requesting too much.

Flickr offers a trimmed down version of their API that’s freely accessible and doesn’t require a key. The Flickr feeds page list urls that let you do this. We’ll be using the public feeds one. It let’s you search for posts by a particular user or tag. By default,, the result it gives you is in XML, but to request JSON just add the query string:

Screen Shot 2014-10-22 at 1.02.29 PM

Still, that’s hard to read, so chrome has a JSONview extension which helps.

Screen Shot 2014-10-22 at 1.03.29 PM

It lists out helpful properties. The items property is formatted like a JS array, where each value contains info for a photo, like its title, where it can be found, and a link to a thumbnail sized image.

Now, remember the issues with requesting info from another web server via AJAX. The solution – browsers let you link to other types of files like CSS, images and JS ones, so we link to a JS file on the Flickr server. The trick is Flickr is really sending us the photo data wrapped in a JS file, accomplished using JSONP, which loads the JS file from another server.

Beginning the project

Goal here is to make a site that loads images from flickr based on certain tags. Here’s the game plan:

Screen Shot 2014-10-22 at 1.12.01 PM

We’ll start with the $(document).ready function since we’re linking to it at the beginning of the file. Now we want to select the word on the button. We’ll select anything with the tag button, then use the .click() helper method, which will add a click event handler to each of the buttons, meaning it will run its function each time one of the buttons is clicked.

Screen Shot 2014-10-22 at 1.33.51 PM

First thing is we want to highlight the clicked button. Let’s do this by adding a class to the clicked button. Remember, “this” means that the class will only be added to the one that was clicked, and not the other ones.

Screen Shot 2014-10-22 at 1.36.57 PM

This is good in that it highlights that button, but bad in that it remains highlighted if we click another. So, we’ll make it remove the class from all the buttons whenever a button is clicked, then add the class to the button that was clicked using this.

Screen Shot 2014-10-22 at 1.37.21 PMScreen Shot 2014-10-22 at 1.38.15 PM

Making the AJAX Request

Now it’s time to make a JSON call using the getJSON() method. We want to send it when a visitor presses on of the buttons, so we’ll put it inside the click event as well. Remember, it takes three arguments, the url to the resource, any additional data, then the callback function.

We add “?jsoncallback=?” query string to the url to tell flickr we’re making a JSONP request, and let’s us get around security limitations.

Screen Shot 2014-10-22 at 1.57.41 PM

Next step, we need to send data, using the flickOptions variable. We need to send different things depending on which button is clicked. We can use the .text() method to get all the text inside the element along with “this” again. Flickr is expecting the data in the form of a JS object, so make a variable with flickOptions and set it equal to an object. We’ll set the tags‘ key value equal to the animal variable, which contains the word of the button pressed. The options available for the keys in the object we send as data are listed here. We can also use the format key to say we want JSON instead of XML.

Screen Shot 2014-10-22 at 2.04.50 PM

Now to do the callback function. You’ll see it receives one argument, named data, represents the JSON data returned by jQuery, which has been parsed into usable JS.

Screen Shot 2014-10-22 at 2.08.05 PM

Note that you can also just plug everything in directly to the getJSON() method rather than create variables.

Screen Shot 2014-10-22 at 2.07.43 PM

Now to write the HTML to display the photos. First we’ll create a variable photoHTML that will contain the html that we can add to. Since we’re doing this 4 times in a row for four pictures, we’ll use a loop via the .each() method. It’s structure looks like this:

Screen Shot 2014-10-22 at 2.21.22 PM

It takes two arguments, an array and a callback function that is applied to each thing in that array. The i is the index value of the item, and the item is the actual value. Here’s an example of how this would work.

Screen Shot 2014-10-22 at 2.23.12 PM

You could also write this using a simple for loop in JS, like below, but jQuery makes it easier.

Screen Shot 2014-10-22 at 2.24.10 PM

Ok, so data is the JSON we received back as JS, and the items property contains all the properties we need. So, we write data.items. NOTE: you can call the arguments whatever you want. We’ll stick with i for index, but change item to photo since that makes more sense.

First, we’ll add the opening list item tag. Then we’ll add the link, getting the href value from the property. Remember, we’re using photo there because we defined that as our value for the index specified. data.items just says what overall array we’re referencing. Then, we want to add an image tag, with the source from We’ll then close the a and li elements. Finally, we close the ul tag outside of the loop, and add this variable to the html of our page.

Screen Shot 2014-10-22 at 2.33.01 PM

Screen Shot 2014-10-22 at 2.52.44 PMScreen Shot 2014-10-22 at 2.52.53 PM

New project – make it so you can enter a word and search for a tag, rather than having to click a button.

Screen Shot 2014-10-22 at 2.57.08 PM

Pretty much just change the event handler to work for form submits, then change the tags value to what the person entered.

Screen Shot 2014-10-22 at 3.08.03 PM

To improve it, let’s disable the input and change the submit button while the AJAX request is running.

Screen Shot 2014-10-22 at 3.14.15 PM

But, we also need to reenable them once the form is done. We’ll do that by adding them at the end of the AJAX callback function.

Screen Shot 2014-10-22 at 3.16.35 PM

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s