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 block | Meaning |
|---|---|
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 |
await | wait for the result; other JavaScript runs in the meantime |
async | marks a function that awaits; awaiting in a non-async function is an error |
x => expr | shorthand 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 declaredasync) 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 functionsasync/await/thenhandle 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#
- Slides 10, p. 10 (
fetch), p. 11 (asynchronous functions), p. 12 (async/await/then), p. 13 (promises), p. 14 (=>), p. 15 (JSON) - DBIS_VL10 > Communicating with other machines via
fetch, DBIS_VL10 > Asynchronous functions, DBIS_VL10 >async,await,then, DBIS_VL10 > Promises, DBIS_VL10 > The=>operator, DBIS_VL10 > JSON - DBIS Exam WS2223 (not published) T4.3, DBIS Exam WS2324-2 (not published) T4.3, DBIS Exam WS1920 (not published) T3.2, DBIS Exam WS2122 (not published) T4.2, DBIS Exam WS1516 (not published) T3