Study Vault Search notes, aliases and full text
Graph
ConceptDBISAI-written · not yet proofread

AJAX and Fetch API

Also AJAX · Fetch API · fetch

AJAX is sending HTTP requests from JavaScript asynchronously, without reloading the page, and updating only part of the page with the result; the modern way is the fetch API, which returns a promise that is processed with async/await and then.

Formula#

// await + then: the course's standard pattern
async function myFct() {
  const response = await fetch("api?query=42").then(response => response.text());
}

// Basic GET request returning JSON
let response = await fetch("/backend?q=" + query);
let data = await response.json();

// Or with .then() chaining only
fetch("/backend?q=" + query)
    .then(r => r.json())
    .then(data => {
        document.querySelector("#result").textContent = data.class;
    });
Building blockMeaning
fetch(url)asynchronous; first yields the response object (status + headers)
.then(f)when the result of the asynchronous function is ready, process it with f
response.json()body parsed as JSON (object/array)
response.text()body as a raw string
awaitwait for the result; other JavaScript runs in the meantime
asyncmarks a function that awaits; awaiting in a non-async function is an error
x => exprshorthand for function(x) { return expr }; several arguments (a, b) => …

Asynchronous execution#

  • JavaScript is single-threaded: at every point in time at most one line of JavaScript is executed. Asynchronous functions (fetch, setTimeout, functions declared async) spend part of their time outside the JavaScript execution, e.g. waiting for the server; meanwhile other JavaScript runs. Real multithreading in the browser needs web workers.
  • A promise is the object returned by an asynchronous function: its status "pending", "fulfilled" or "rejected", plus the result once fulfilled. It can be built explicitly, new Promise((resolve, reject) => …), but for built-in functions async/await/then handle promises implicitly.

JSON#

JSON (JavaScript Object Notation) is content that is already JavaScript literal syntax: arrays [2, 3, 5], maps {"query": "6*7", "result": "42"}, strings, numbers. The server sends it with Content-Type: application/json; after .then(r => r.json()) the object is used directly: response[2] (third array element), response.result (value for a key).

jQuery AJAX (deprecated)#

$.get("/backend?q=" + query, function(result) {
    $("#result").html(result);
});

The callback receives the already parsed body (a JSON array arrives as an array).

Properties#

  • Requests are asynchronous: the page remains interactive while waiting for the response.
  • No page reload occurs, only the targeted DOM element is updated. Contrast: an HTML Form submission loads a whole new page.
  • The response from the server is typically JSON with Content-Type: application/json.
  • Special characters in the URL are URL-encoded as UTF-8 bytes by fetch (ä → %C3%A4). + and & in the input are not escaped by plain string concatenation; encodeURIComponent(q) escapes them too.
  • A relative URL ("/api?query=…") goes to the server the page came from; an absolute URL to another host+port is subject to the Same-Origin Policy (CORS).
  • Typing fast produces concurrent requests, so answers may arrive out of order and the server should handle requests in parallel (HTTP Server > Concurrency).

Example#

Sources#

Search

Type In
↑ ↓ move ↵ open ⇥ next section Ctrl↵ results page Prefix # to search text only