AJAX (legacy)

AJAX (Asynchronous JavaScript and XML) is a technique for communicating with a server withoutreloading the entire web page.Popularized in the early 2000s, AJAX originally relied on XMLHttpRequestand often used XML to exchange data.Today, developers typically use the modern fetch()API with JSON, but the underlying AJAX concept remains the same.

You'll still see it out there in the wild. It probably won't say "AJAX" anywhere in the JS (that's just the name of the tech). More likely you'll see something like const xhr = new XMLHttpRequest();. That tells you you're dealing with AJAX. Then later on, you'll see method calls on the xhr object to do the partial page reloads, etc.

Read W3Schools AJAX intro

Fetch (modern)

fetch() is a built-in JavaScript function. We call it part of an API (Application Programming Interface) because it provides a standard way for your JavaScript code to interact with the browser's networking capabilities.

Conceptual Fetch workflow:

You make a plan for your butler to prepare dinner. You write down a series of tasks:

  • FETCH a chicken from the store, and when travel, transaction, etc is done RETURN with the raw chicken
  • THEN take the chicen you returned with; after you marinate it, season it, cook it RETURN with dinner
  • THEN take the dinner you returned with; after you serve it, wait for us to eat, RETURN with dishes
  • THEN take the dishes you returned with, and wash them. Done.
  • Meanwhile, during any of those downtimes (waiting for chicken to cook, waiting for us to eat, etc.), you can go ahead and do you're regular things: answer the door bell, respond to a mouse click, etc. No need to stand around doing nothing while you wait.
  • Caveat: If anything blocked you alon the way (store closed, oven broken), THROW a fit (an error) so you don't have to keep trying to do task without the stuff you need.
  • We'll CATCH the problem (the error) and deal with having no dinner.

Each THEN receives the result of the previous task. Each RETURN passes a value along to the next task. If a task fails, the remaining steps are skipped and control passes to CATCH.

You're describing a sequence of tasks that depend on one another, without having to perform them all at once or block everything else while you wait.

Read MDN Using the Fetch API

Check Your Understanding

  • Why might you need an API key to use a third-party API service?

    • Think about paying for the chicken. How does the service know who you are, whether you're authorized to use it, and whom to charge?

  • Why are JavaScript Promises so important to the Fetch API?

    • Think about the state of each task: pending, fulfilled, or rejected.

    • How do Promises allow JavaScript to handle other events while waiting for a response?

    • How does the result of one task get passed to the next?