AJAX

AJAX enables

AJAX Examples

AJAX Definition

Asynchronous JavaScript And XML

  1. Request data from an external source
  2. Parse the data returned by the request
  3. Load that data into the page without a refresh
  4. Data can be any formats, most common:
    • XML
    • JSON
    • HTML fragment (not an entire page)

AJAX Advantages/Disadvantages

Advantages

Disadvantages

AJAX History

[0] http://adaptivepath.org/ideas/ajax-new-approach-web-applications/

Jesse James Garrett Quote

(corrected for modern use)

Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

This was the moment that people realized web applications could be a competitor to desktop applications, and could run on every computer in the world.

XMLHttpRequest (Old Way)

WARNING: DO NOT READ THIS CODE CAREFULLY

var httpRequest;

function sendRequest() {
  httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = printResponse;
  httpRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
  httpRequest.send();
}

function printResponse() {
  if (httpRequest.readyState === XMLHttpRequest.DONE) {
    if (httpRequest.status === 200) {
      console.log(httpRequest.responseText);
    } else {
      console.log('There was a problem: ' + httpRequest.status);
      console.log({httpRequest})
    }
  }
}

Browser Fetch API - Plain Text

The Fetch interface is concise

https://jsonplaceholder.typicode.com/posts/1

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    console.log(response.status);
    return response.text();       // body is not quite ready yet
  })
  .then(function(text) {
    console.log(text);            // now the body is ready
  });

Why Two Thens?

Browse Fetch API - JSON

let postNumber = 1;
fetch('https://jsonplaceholder.typicode.com/posts/' + postNumber)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

Browser Fetch API - Local

If you want to request data from a local webserver, use a partial URL

fetch('/city-market.md')
  .then(function(response) {
    return response.text();
  })
  .then(function(myText) {
    console.log(myText);
  });

Browser Fetch API - Errors


fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    if (!response.ok) {
      console.log('HTTP error: ' + response.status);
    } else {
      return response.json();
    }
  })
  .then(function(json) {
    console.log(json);
  })
  .catch(function(error) {
    console.error('Network error:\n', error);
  });

JSON (JavaScript Object Notation)

See a more comprehensive JSON lesson here: JSON lesson

Example

{"userId": 1,
  "id": 1,
  "title": "My most amazing post",
  "body": "This is my first post, isn't it great. Maybe I'll write some more."
}

NOTE:

Parsing & Producing JSON

The Fetch API converts text into JSON for you if you call response.json()

but if you want to do it yourself...

JSON.parse converts a string into an object:

let data = JSON.parse(string)

So this would work fine:

fetch('/city-market.json')
  .then(function(response) {
    return response.text();
  })
  .then(function(myText) {
    let myObject = JSON.parse(myText);
    console.log(myObject);
  });

 Previous Lesson Next Lesson 

Outline

[menu]

/