...

/

Tip 45: Make Simple AJAX Calls with Fetch

Tip 45: Make Simple AJAX Calls with Fetch

In this tip, you’ll learn how to retrieve remote data using fetch().

AJAX calls

If you do any significant JavaScript app development, you’ll have to interact with APIs. With APIs, you can get current information and update single elements without a page refresh. In short, you can create very fast applications that behave like native software.

Single-page web apps are part of the reason why JavaScript is so popular, but getting data with AJAXAsynchronous JavaScript And XML—used to be a hassle. It was such a hassle that most developers used a library, usually jQuery, to to reduce the complexity. You can see the documentation on the Mozilla Developer Network. It’s not easy stuff.

Using fetch()

Now, there’s a much simpler tool for AJAX calls: fetch(). This tip is a little different than the others. fetch() isn’t part of the JavaScript spec. The fetch spec is defined by the Web Hypertext Application Technology Working Group or WHATWG. That means you’ll be able to find it in most major browsers, but it isn’t natively supported in Node.js. If you want to use it in Node.js, you’ll need to use the node-fetch package. ...