No description, website, or topics provided.
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
LICENSE.txt
README.md

README.md

AJAX

Why is this important?

This workshop is important because:

AJAX is a fast, user-friendly way to access data from external resources, when that data is available through a web API.

In order to make complex web apps, we will probably want information from some of the amazing resources that provide rich, useful data. If you want to integrate maps, social media, live searched images, or any other user controlled data, you're going to want to use an API. If you want to reduce page refreshes from HTTP requests/reponses, AJAX is the tool for you!

What are the objectives?

After this workshop, developers will be able to:

  • find and read documentation for useful web APIs
  • explain the difference between AJAX and normal HTTP synchronous web data transfer
  • use AJAX with jQuery's $.ajax to GET data from an API
  • describe the meaning of method:, url:, and success: keys in jQuery's $.ajax syntax
  • give an example of where AJAX would be used in code for a website

Where should we be now?

Before this workshop, developers should already be able to:

  • read JSON and access specific attributes of a large piece of JSON
  • explain that callbacks are functions passed around to be executed later
  • describe the request-response cycle and HTTP's role in it

Review

  1. Explain the diagram below.

  1. Go to this piece of JSON. Assume that the entire object returned is called response and answer the following questions:
  • Looking at the comments added by JSONViewer, where does this data come from? What search term generated this data?
  • How would you access the fixed height image URL of the first result?

catz

APIs

API gif

An Application Program Interface (API) is the way in which you interact with a piece of software. In other words, it is the interface for an application or a program.

  • You've browsed jQuery's API documentation - http://api.jquery.com/. jQuery's API is basically the set of objects and functions it gives us above and beyond standard JavaScript.
  • Even a vanilla JavaScript Array has an API. Its API consists of all the methods that can be called on it, such as: .forEach, .pop, .length etc. See the full list: Object.getOwnPropertyNames(Array.prototype).
  • Organizations have web APIs to publicly expose parts of their services to the outside world, allowing people to send them queries and receive data (e.g. GitHub API ). Web APIs are the kind of APIs we'll focus on today.

When we read the documentation for an API, you can compare it to a contract. The documentation explains how you can interact with an API, and defines how the API will respond to your requests.

Some useful APIs

Food2Fork, Twitter, Spotify, Google Books, Google Maps, WeatherUnderground, Giphy, YouTube, etc.

Learning to use an API

A GUI (graphical user interface) exists to make an application more convenient for a sighted user to interact with visually. An API does something similar - except its users are developers, and they interact with the API through programming languages and specific protocols. Learning to use an API is a little like learning to use a new application on your computer. Here are a few ways they're alike:

  • You have to follow the rules set out by the API or GUI.
  • You can make guesses and experiment, but it's easier to start with some documentation.
  • Practice using APIs or GUIs helps you find patterns that carry over to other programs.

First Encounter with an API

Follow along as I show you how I'd initially investigate the Spotify API.

  1. Find documentation.
  2. Check for any restrictions (authorization, API key, wait time for approval, etc.).
  3. Pick an endpoint to try (GET routes work best for exploration!).
  4. Try to go to that endpoint and inspect some data.

Breakout

With a partner, spend 10 minutes on the following:

  • Find an API on the internet, look at the documentation, and answer these questions:
    1. What format of data does this API return?
    2. How would you access the data that you're interested in? For example, for Giphy, the gif data that we're interested in is located in the data array.
    3. Does this API require an API key?
    4. Can you view an API endpoint url in your browser? Do it!

AJAX

Asynchronous JavaScript And XML (AJAX) allows us to make requests to a server (ours or another application's) without refreshing the page.

Let's break that down:

Asynchronous - not happening at the same time. Some of your code will be executed at a later time. Specifically, a callback will run when you get the results of your request - even if takes a while. This waiting time won't hold up the performance of the rest of your page.

XML - a format for structuring data so that it can be sent and received across the web. XML has mostly been replaced by JSON, and AJAX can be used with either JSON or XML.

You may also hear the term XMLHttpRequest. This is how vanilla JavaScript does AJAX. In fact, window object in the Browser has available to it another object, XMLHttpRequest. JavaScript's XMLHttpRequests are notoriously annoying to create, so jQuery's shorthand (the $.ajax() function) is one of jQuery's most popular features.

Why do we care?

  • In the past, requests had a "synchronous" workflow, where the user had to wait for the request to come back before anything else could happen on the page. Synchronous requests also require the page to reload.

  • AJAX lets us exchange data with the server behind the scenes. When a change is made on the client, we can use AJAX to send a request and notify the server of what just happened. This is an important way to maintain state between a client and a server that communicate in HTTP, an inherently stateless protocol.

  • Limiting page reloads makes our web apps feel faster and mostly gives our users a better experience. Imagine if you experienced a full page refresh every time you "liked" a post on Facebook.... The requests we've made so far have been synchronous.

AJAX is the doorman! It knows what requests are out and what to do when they return. The code (hotel) can keep operating without waiting for a single request (guest) to complete.

How do we use AJAX?

jQuery gives us several methods for making AJAX requests. We're going to stick to using the $.ajax() method available here.

GET and POST

The HTTP protocol was designed specifically for web browsers and servers to communicate with each other in a request/response cycle.

GET and POST are the most common verbs used in HTTP requests:

  • A browser will use GET to indicate it would like to receive a specific web page or resource from a server.
  • A browser will use POST to indicate it would like to send some data to a server.

Conveniently, we can use AJAX to make both GET and POST requests to servers. From the perspective of the server, it is just another request.

jQuery gives us the $.ajax() method, which will allow us to perform any AJAX request.

AJAX Setup

Using jQuery's $.ajax() method, we can specify several parameters. Here's a good set to start with:

  • kind of request (verb)
  • request URL
  • data type
  • callback function (which will run on successful completion of the AJAX request)

Here's some examples of the data we'll be looking at: http://api.giphy.com/v1/gifs/search?q=nice&api_key=dqdTxiHetp6t9S7rrkvJVR5FlPviedf1&limit=5

Let's try sending a GET request to Giphy's API

// defining the callback function that will happen
// if the request succeeds.
function onSuccess(responseData) {
    console.log(responseData);
    // celebrate!
}

$.ajax({
  // What kind of request
  method: 'GET',

  // The URL for the request
  url: 'http://api.giphy.com/v1/gifs/search?q=nice&api_key=dqdTxiHetp6t9S7rrkvJVR5FlPviedf1&limit=5',

  // The type of data we want back
  dataType: 'json',

  // Code to run if the request succeeds; the JSON
  // response is passed to the function as an argument.
  success: onSuccess
})

For a POST request, we can also use the $.ajax() method, but this time, the request type is "POST". Since POST requests send data to a server, we also need to send an object or string for data (the bookData in the example below).

var bookData = {
  title: "The Giver",
  author: "Lowis Lowry"
};

$.ajax({
  method: "POST",
  url: "/books", // this is a "relative" link
  data: bookData,
  dataType: "json",
  success: onSuccess
});

function onSuccess(responseData) {
  console.log(responseData);
  // celebrate!
};

AJAX and Event Handlers

We can combine AJAX calls with any jQuery event handlers. You may want to execute an AJAX call when the user clicks and button or submits a form.

var endpoint = 'http://api.giphy.com/v1/gifs/search?q=nice&api_key=dqdTxiHetp6t9S7rrkvJVR5FlPviedf1&limit=5'

// click event on button
$('button').on('click', function(event) {
  $.ajax({
    method: 'GET',
    url: endpoint,
    dataType: 'json',
    success: onClickReqSuccess
  });
});

function onClickReqSuccess(responseData){
  console.log(responseData);
  // process data
}

// submit event on form
$('form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
    method: 'GET',
    url: endpoint,
    dataType: 'json',
    success: onSubmitReqSuccess
  });
});

function onSubmitReqSuccess(responseData){
  console.log(responseData);
  // process data
}

Often, we'll need to send data to an API in order for it to process our requests. For example, the Giphy API requires a q query paramater for the search endpoint. You've seen that we can include a data key in a $.ajax() call. When searching Giphy with $.ajax(), we could use an object or a string to indicate the value of q.

// submit event on form
$('form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
    method: 'GET',
    url: endpoint,
    data: 'q=cats',
    dataType: 'json',
    success: onSubmitReqSuccess
  });
});

function onSubmitReqSuccess(responseData){
  console.log(responseData);
  // process data
}

If this data comes from the user, it will often be in a form. Luckily, jQuery provides a method called serialize() that translates form data into a string. Then, we can easily plug the result into the data attribute, like this:

// submit event on form
$('form').on('submit', function(event){
  $.ajax({
    method: 'GET',
    url: endpoint,
    // The data to send (query parameters)
    data: $("form").serialize(),
    dataType: 'json',
    success: onSubmitReqSuccess
  });
});

function onSubmitReqSuccess(responseData){
  console.log(responseData);
  // process data
}

As long as the form <input> fields have the proper name attribute (in this case, q), serialize() will make our perfect object!

<input type="text" class="form-control gif-input" name="q" placeholder="search gifs">

Handling Success and Failure

When everything goes well, we'll get a response with an HTTP status in the 200s. The $.ajax function checks this status to see if the request was sucessful. If the status is in the 200s, it runs the success callback.

We can't guarantee that an API will respond or respond quick enough. In these cases, the AJAX request will fail or give an error. Using the $.ajax() syntax, we can handle these cases by including error and complete attributes on our initial request:

var endpoint = 'https://api.spotify.com/v1/search?q=come%20together&type=track';

$.ajax({
  method: 'GET',
  url: endpoint,
  dataType: 'json',
  success: onSuccess,
  error: onError,
  complete: onCompletion
});

function onSuccess(responseData, status, xhr){
  /*  perform this function if the
     status code of the response was in
     the 200s */
};

function onError(xhr, status, errorThrown){
  /* perform this function if the
     response timed out or if the
     status code of the response is
     in the 400s or 500s (error)
     xhr: the full response object
     status: a string that describes
     the response status
     errorThrown: a string with any error
     message associated with that status */
};

function onCompletion(xhr, status){
  /* perform this no matter the status
     code of the response */
};

Independent Practice

Refine the skills covered in this workshop with this Giphy API training.

For a solution including the bonus checkout the solution-more branch or find it here on GitHub.

Closing Thoughts

  • APIs open an entire world of more complex projects! All you need to access them is an understanding of HTTP. Now, though, you can access them using AJAX for a smoother, faster user experience.
  • The syntax of the $.ajax() function is complicated, but more practice will familiarize you with its uses and complexity. Check in on whether you can explain method:, url:, and success: without any outside resources.
  • Later, we'll be working with APIs that we can POST data to and update data in databases.

Additional Resources