Basics: Using AJAX with Fetch API

Benjamin Cunningham
letsboot
Published in
2 min readMar 15, 2018
Jaguar Mk II — also named Ajax

Check out our Angular in-house trainings or a public Angular courses.
Try out fossilo.com, our angular project to archive complete websites.

Today we want interactive websites. So after a website is loaded we often need to save something to the server or get new data from it. For that we don’t want to always reload the page so we need something to connect to a server, an API, through JavaScript. That’s what AJAX is for.

AJAX stands for Asynchronous JavaScript And XML. AJ represents that code is executed asynchronously, and XML distributes data over the internet through browsers. The term AJAX is a bit outdated, as we don’t often use XML anymore.

Originally the XMLHttpRequest API was the working standard for many years until other APIs were created to simplify the code confusion. The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline for requests and responses using promises. Fetch also provides a global fetch() method that logically and simply fetches resources asynchronously across the network.

To show the difference with the first API called XMLHttpRequest and Fetch, check the following example:

XMLHttpRequest Example

And here is the example using the Fetch API:

Fetch Example

Check out another example explained in detail:

Here are some other useful methods that you can use with the Fetch API:

  • clone(): creates a clone of the response
  • redirect(): creates a new response but with a different URL
  • arrayBuffer(): returns a promise that resolves with an array buffer
  • formData(): returns a promise that resolves with a form data object
  • blob(): resolves with a blob
  • text(): resolves with a string
  • json(): resolves the promise with JSON

Fetch is a great API to use for asynchronous execution of code. It is however created for ECMA script 6, but now most browsers are updated to using ES6, so it’s good apart from the Opera browsers. Personally, I’d much rather use fetch than the XMLHttpRequest API because I prefer simple and easy to read code.

https://caniuse.com/#feat=fetch

--

--

Benjamin Cunningham
letsboot

I live in Basel, CH and I aim to become a front end web developer. I have started working as a Co-Trainer and a Software Engineer at Letsboot.