AJAX

AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to update data without having to refresh the entire page. Using JavaScript we can send requests to the server in the background and then update only the necessary part of the page with the response data. The server-side code typically returns data in a lightweight format such as XML or JSON.

Weirdly, it's still called AJAX even if we don't use XML much with AJAX anymore.

How do we make AJAX requests?

The native implementation is to use XHR (XML HTTP Request objects). This is the way AJAX is implemented natively in the browser (as a Web API). But XHR code is quite long, see an example here.

So instead of writing XHR ourselves, we can use the newer fetch browser API or a 3rd party library that does it for us e.g. Axios: https://github.com/axios/axios

Fetch API

fetchis similar to XHR but more powerful and has less overhead in how we use it.

const movie = fetch('http://omdbapi.com?apikey=2f6435d9&t=sharknado')
console.log(movie.Title) // => undefined

AJAX requests are asynchronous so the code above won't work because we don't receive the movie immediately. fetch returns a Promise so we need to use .then:

fetch('http://omdbapi.com?apikey=2f6435d9&t=sharknado)
  .then(response => response.json())
  .then(response => console.log(response))

Axios

Axios is a popular library for making AJAX requests. It has a few features that the native fetch isn't capable of (yet).

This is a 3rd-party library so we need to include it in a script tag first:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
axios
  .get("http://omdbapi.com?apikey=2f6435d9&t=sharknado")
  .then(response => console.log(response))

Last updated