{"id":254018,"date":"2017-05-02T05:54:46","date_gmt":"2017-05-02T12:54:46","guid":{"rendered":"http:\/\/css-tricks.com\/?p=254018"},"modified":"2020-11-12T13:05:29","modified_gmt":"2020-11-12T21:05:29","slug":"using-fetch","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/using-fetch\/","title":{"rendered":"Using Fetch"},"content":{"rendered":"\n
Whenever we send or retrieve information with JavaScript, we initiate a thing known as an Ajax call. Ajax is a technique to send and retrieve information behind the scenes without needing to refresh the page. It allows browsers to send and retrieve information, then do things with what it gets back, like add or change HTML on the page.<\/p>\n\n\n\n\n\n\n\n
Let’s take a look at the history of that and then bring ourselves up-to-date.<\/p>\n\n\n\n
fetch(URL)\n .then(response => response.json())\n .then(data => {\n console.log(data)\n });<\/code><\/pre>\n\n\n<\/details>\n\n\n<\/p>\n<\/div><\/div>\n\n\n\n
Another note here, we’re going to be using ES6 syntax for all the demos in this article.<\/p>\n\n\n\n
A few years ago, the easiest way to initiate an Ajax call was through the use of jQuery’s ajax<\/code> method:<\/p>\n\n\n\n$.ajax('some-url', {\n success: (data) => { \/* do something with the data *\/ },\n error: (err) => { \/* do something when an error happens *\/}\n});<\/code><\/pre>\n\n\n\nWe could do Ajax without jQuery, but we had to write an XMLHttpRequest<\/code>, which is pretty complicated<\/a>.<\/p>\n\n\n\nThankfully, browsers nowadays have improved so much that they support the Fetch API, which is a modern way to Ajax without helper libraries like jQuery or Axios. In this article, I’ll show you how to use Fetch to handle both success and errors.<\/p>\n\n\n
Support for Fetch<\/h3>\n\n\n
Let’s get support out of the way first.<\/p>\n\n\n
This browser support data is from Caniuse<\/a>, which has more detail. A number indicates that browser supports the feature at that version and up.<\/p><\/div>Desktop<\/h4>