Web Applications

JavaScript Fetch

Objectives

  • Promise & async/await
  • AJAX with Fetch API
  • Exercise: My first GET
  • Exercise: My first POST
  • Exercise: Your National Open Data Catalog
  • Exercise: Submit HTML form

Promise

Represents the eventual completion (then()) or failure (catch()) of an asynchronous operation. Promises can be chained. More about promises in other seminar.


doSomethingAsynchronouslyAndReturnPromise()
  .then(function (result) { return transformTheResult(result); })
  .then(function (finalResult) {
    console.log("Got the final result: " + finalResult);
  })
  .catch(failureCallback);
    

Promise with async/await


try {
  const result = await doSomethingAsynchronouslyAndReturnPromise();
  const finalResult = transformTheResult(result);
  console.log("Got the final result: " + finalResult);
} catch (exception) {
  failureCallback();
}
    

AJAX

Asynchronous background HTTP requests to the server without reloading page invoked from JavaScript. The request can utilize HTTP method (GET, POST, DELETE, ...) and contain user defined data. Typically exchanging JSON data, but can be other types (text, HTML, binary, ...).

Data can be send encoded in URL (GET, POST, ..) or in request body (POST, "PUT"). We can send encoded JSON using the body or structure the content with FormData.

Cross-Origin Requests

Cross-origin network access (CORS) is using HTTP readers to control AJAX. Bellow is an example of HTTP response headers allowing anyone to perform GET and POST.


access-control-allow-methods: GET, OPTIONS
access-control-allow-origin: *
    

CORS is implemented and enforced by browsers. Users are still able to execute request by other means!

Cross-origin resource sharing (CORS) is the SELinux of the Web. You really want to do the right thing but it only works when you: "Access-Control-Allow-Origin", "*"

await fetch("https://mff.cuni.cz/");
// See Network tab.
    

Demonstration: Fetch API


function fetchData(url) {
  fetch(url)
    .then(response => response.json())
    .then(data => console.log("Got the data: " + data))
    .catch((error) => console.log("Can't fetch data", error));
}
    

Alternative implementation using async/await.


async function fetchData() {
  try {
    const response = await fetch(url);
    const data = await response.json(); // Use .text() to get text content.
    console.log("Got the data:", data);
  } catch(error) {
    console.log("Can't fetch data", error);
  }
}
    

Exercise: My first GET

Create an first-fetch.html file on a local machine. The page should contain a button with label "Action". When user click the fetch JSON from 10-anywhere-json.php. Extract message from JSON response and set it as page content.

Make sure your website is valid.

Exercise: My first POST

Create website at webik.ms.mff.cuni.cz in your public_html directory. Use JavaScript to POST JSON at 10-json-processing.php. You need to post JSON of following shape:


{ "name": "Pavel", "position": "Teacher" }
  

Once you get the response render it on your page.
You can specify additional options (body, method) for fetch using the second argument.

Exercise: Your National Open Data Catalog

Download this page and resolve all TODOs. The objective is to have custom implementation of the catalog build upon GraphQL endpoint of Czech National Open Data Catalog.

Exercise: Submit HTML form

Download this page and resolve all TODOs.

The aim is to handle form submission using JavaScript.

How are we doing?

  • Promise & async/await
  • AJAX with Fetch API
  • Exercise: My first GET
  • Exercise: My first POST
  • Exercise: Your National Open Data Catalog
  • Exercise: Submit HTML form
Questions, ideas, or any other feedback?

Please feel free to use the anonymous feedback form.