2023-05-17 - AJAX


main topics


fetching data from an API

Summing up: This day was filled with challenges to use structures like this:

// performing a GET request
fetch(url)
  .then(res => res.json())
  .then((data) => {
    // do something with the json payload
    // inside the 'data' variable as a string
  });

// performing a POST request
fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(aJsonPayload)
  })
  .then(res => res.json())
  .then((data) => {
    // check if the server returned
    // something useful after the POST
    // e.g.: a status code.
  });

Of course the challenges were also about figuring about how to use the JSON returned by the APIs (reading API docs or even inspecting the JSON).

preventDefault() to prevent page reload

Some challenges were about avoiding the reload of the page after submitting a form. It usually goes like this:

const form = document.querySelector("#search-form");

form.addEventListener("submit", (event) => {
  event.preventDefault(); // don't submit the form
  const input = event.currentTarget.querySelector(".form-control");
  searchMovies(input.value);
})