AJAX

Asynchronous

JavaScript

and

XML

Not a great name...

AJAX IS NOT...

  1. A Library
  2. A Framework
  3. A Technology

AJAX IS...

an approach

(that's it)

JavaScript

HTML

The DOM

CSS

BACK IN 2005ish

"Hey wait a minute, all the pieces are here for us to make web apps that can update without refreshing!"

XMLHTTP Requests

What it boils down to

With AJAX, websites can send and request data from a server in the background without disturbing the current page

Today's Single Page Apps

How does Pinterest keep loading new content forever?!

AJAX!

Compare that with Reddit...

AJAX!

NOT

JavaScript

Server

"The user scrolled to the bottom!"

"Quick, send a request to the server and get more content!"

yeah, yeah here you go

"Now I'll just append the new data to the bottom of the page"

JavaScript

Server

"The user scrolled to the bottom!"

"Quick, send a request to the server and get more content!"

yeah, yeah here you go

"Now I'll just append the new data to the bottom of the page"

What This Section Is Really About

Making Requests with JavaScript

  1. XMLHTTP Request
  2. The Fetch API
  3. 3rd Party Libraries: jQuery, Axios, etc.

Asynchronous

JavaScript

and

XML

What's The Deal With This?

XML AND

JSON

Data formats

"Quick, send a request to the server and get more content!"

Server

WHAT DOES THE DATA LOOK LIKE?

API's don't respond with HTML. API's respond with pure data, not structure.

They use more efficient data formats like XML and JSON

Data Formats

XML

<pin>
  <title>Adorable Maine Coon</title>
  <author>Cindy S</author>
  <num-saves>1800</num-saves>
</pin>

Extended Markup Language

XML is syntacticly similar to HTML, but it does not describe presentation like HTML does

JSON

'pin': {
  'title': 'Adorable Maine Coon',
  'author': 'Cindy S',
  'num-saves': 1800
}

JavaScript Object Notation

JSON looks (almost) exactly like JavaScript objects

JSON is more commonly used these days because it works so well with JavaScript

JavaScript Object Notation

It's in the name!

Asynchronous

JavaScript

and

JSON

Doesn't quite have the same ring to it

Making Requests with JavaScript

  1. XMLHTTP Request
  2. Fetch API
  3. 3rd Party Libraries: jQuery & Axios

XMLHTTP Requests

Quite A Mouthful 

var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
    if (XHR.readyState == 4 && XHR.status == 200) {
      console.log(XHR.responseText);
    }
};
XHR.open("GET", "https://api.github.com/zen");
XHR.send();

Our First AJAX "App"

WHAT ABOUT POST REQUESTS??

var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
  if (XHR.readyState == 4 && XHR.status == 200) {
    console.log("it worked!");
  }
};

var url = "www.blah.com";
XHR.open("POST", url);
XHR.send("some data");

XMLHTTP Post Requests

Typically Form Data

YOUR

TURN

Live Bitcoin Price Exercise

PROBLEMS WITH XHR

  1. Ugly, Bulky Syntax
  2. It's 16 Years Old
  3. No Streaming

ENTER THE FETCH API

fetch(url)
.then(function(res) {
  console.log(res);
})
.catch(function(error) {
  console.log(error);
});

This Is How You Make Fetch Happen

Look at that clean syntax!

fetch(url).then(function(res) {
  return res.json();
}).then(function(data) {
  console.log(data);
}).catch(function() {
  console.log("problem!");
});

Parsing JSON with Fetch

Fetch Options

fetch(url, {  
    method: 'POST',  
    body: JSON.stringify({
        name: 'blue',
        login: 'bluecat',
    })
})    
.then(function (data) {  
  //do something 
})  
.catch(function (error) {  
  //handle error 
});
fetch(url)
.then(function(res) {
    if (!res.ok) {
        throw Error(404); //up to you
    }
    return res;
}).then(function(response) {
    console.log("ok");
}).catch(function(error) {
    console.log(error);
});

Handling Fetch Errors

YOUR

TURN

 fetch(url)
  .then(handleErrors)
  .then(parseJSON)
  .then(updateProfile)
  .catch(printError)

Refactoring Fetch

FETCH IS COOL!

THE ONLY PROBLEM?

😭

AJAX With jQuery

jQuery

"The Write Less, Do More JavaScript Library"

function fadeIn(el) {
  el.style.opacity = 0;

  var last = +new Date();
  var tick = function() {
    el.style.opacity = +el.style.opacity 
    + (new Date() - last) / 400;
    last = +new Date();

    if (+el.style.opacity < 1) {
      (window.requestAnimationFrame && 
        requestAnimationFrame(tick)) 
        || setTimeout(tick, 16);
    }
  };

  tick();
}

fadeIn(el);
$(el).fadeIn();

Without jQuery

With jQuery

The Same Applies For Making Requests!

Making A Request And Parsing JSON

var request = new XMLHttpRequest();
request.open('GET', '/my/url');

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    //do something
  }
};

request.onerror = function() {
  // There was a connection error
};

request.send();
$.getJSON('/my/url', function(data) {

});

Without jQuery

With jQuery

WAYYY

EASIER!

  • $.ajax
  • $.get
  • $.post
  • $.getJSON

jQuery AJAX Methods

Shorthand

Methods

$.ajax({
  method: "GET",
  url: "some.api.com",
})
.done(function(res) {
  console.log(res);
})
.fail(function(){
  //do something
})

$.ajax

The "base" jQuery Method

just creates an XMLHttpRequest under the hood

What about parsing JSON?

Shorthand Methods

YOUR

TURN

IT'S TIME FOR RANDOM CAT PHOTOS

AXIOS

A lightweight HTTP request library

axios.get(url)
.then(function(res){
  console.log(res.data);
})
.catch(function(e){
  console.log(e);
})

axios.get

Makes a get request!

just creates an XMLHttpRequest under the hood

Handling Errors

With Axios

if (err.response) {
  console.log("Problem With Response");
} else if (err.request) {
  console.log("Problem With Request!");
} else {
  console.log('Error', err.message);
}

Handling Errors

Copy of AJAX

By Elie Schoppik

Copy of AJAX

  • 1,824
Loading comments...

More from Elie Schoppik