Code Monkey home page Code Monkey logo

js-intro-ajax's Introduction

Intro to AJAX

Objectives
Students will be able to:
Give examples of useful APIs
Explain why we use AJAX
Use AJAX to GET data from an API

APIs

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.

  • Organizations have APIs to publicly expose parts of their program to the outside world, allowing people to send them queries and receive data (e.g. GitHub API ), but this is a narrow view of what the term fully encompasses.
  • Remember, even an 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).

A GUI exists to make an application more convenient for the user. An API does the same for its users, but with a lexical rather than a graphical interface.

Some useful APIs

Instagram, Food2Fork, Twitter, Spotify, Google Books, Google Maps, WeatherUnderground, etc.

Breakout

With a partner, spend 10 minutes

  • Discussing your understanding of APIs
  • Finding an API on the internet, looking at the documentation, and answering these questions:
    1. What format of data does this API return?
    2. How would you access the data that you'd likely be 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, when you hear back from a server about a request you made sometime in the past. This waiting time won't hold up the performance of the rest of your page.

XML - another format for structuring data so that it can be sent and received. XML has mostly been replaced by JSON and AJAX doesn't require the use of XML.

You may also hear the term XMLHttpRequest. This is the same thing as AJAX! In fact, window object in the Browser has available to it another object, XMLHttpRequest. This is how you would make these types of requests without using jQuery.

Why do we care?

  • AJAX lets us exchange data with the server behind the scenes. When a change is made on the client we can send off an AJAX Request to 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...

How do we use it?

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 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, including:

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

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

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

  // The URL for the request
  url: 'https://api.spotify.com/v1/artists/1jTAvg7eLZQFonjWIXHiiT',

  // 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
});

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

For a POST request, we can also use the $.ajax() method, but this time, the data type is "POST". Since POST requests send data to a server, we also need to send an object of data (the book).

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

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

function onSuccess(json) {
  console.log(json);
  // 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 = 'https://api.spotify.com/v1/search?q=goodbye&type=artist'

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

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

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

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

Handling Success and Failure

We can't guarantee that our API will respond, or will respond quick enough. In these cases the AJAX request will fail or error. Using the jquery.get() shorthand we can handle these eventualities by "chaining" additional listeners to 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(json){
  /*  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(json){
  /* perform this no matter the status
     code of the response */
};

Lab work

Giffaw lab

For a solution, checkout the solution branch or find it here on GitHub.

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

Further Reading

js-intro-ajax's People

Contributors

justincastilla avatar

Watchers

James Cloos avatar Ben Manning avatar

Forkers

hoevik

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.