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:
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.
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:
You could actually do this:
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.
You can also insert the info directly in instead of using variables.
Let’s see how we can replace the load() method with the get() one.
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.
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.
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.
For the array argument, you enter the index number for the value you want, like the i in a for loop.
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.
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.
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.
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:
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.
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.
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.
If you instead use the .statusText property it will explain it via text and you can give that to the user.
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.
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.
AJAX and APIs
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.
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, https://api.flickr.com/services/feeds/photos_public.gne, the result it gives you is in XML, but to request JSON just add the query string: https://api.flickr.com/services/feeds/photos_public.gne?format=json
Still, that’s hard to read, so chrome has a JSONview extension which helps.
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:
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.
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.
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.
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.
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.
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.
Note that you can also just plug everything in directly to the getJSON() method rather than create variables.
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:
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.
You could also write this using a simple for loop in JS, like below, but jQuery makes it easier.
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 photo.link 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 photo.media.m. 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.
New project – make it so you can enter a word and search for a tag, rather than having to click a button.
Pretty much just change the event handler to work for form submits, then change the tags value to what the person entered.
To improve it, let’s disable the input and change the submit button while the AJAX request is running.
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.