⇧
vadnica-logo
My Services About the Project Telegram O meni O meni

JavaScript Fetch API

Although the XMLHttpRequest object ruled AJAX communication for a long time, modern JavaScript introduces a much better, shorter, and more elegant replacement: the Fetch API. Fetch utilizes what we call Promises, allowing us to write much cleaner code without the hassle of complex state tracking (readyState).

EXAMPLE
RESULT

How Does Basic Fetch Work?

The fetch() method takes only one required parameter: the path to the data (URL). Because it works with promises, we chain the responses using the .then() method:

  1. fetch() submits the request to the server.
  2. The first .then() receives the raw response and converts it into text or a JSON object.
  3. The second .then() receives the final data, which we can immediately output to the page.
fetch("alphabet.php?q=A")
    .then(response => response.text()) // Converts raw response to text
    .then(data => {
        document.getElementById("output").innerHTML = data;
    });

Main Advantage: The code is highly readable, contains no complex event listeners, and automatically supports modern data formats like JSON.