A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://sabe.io/classes/javascript/ajax-fetch below:

AJAX and Fetch: JavaScript Tutorial

AJAX

AJAX is a technique for sending or requesting data without have to perform a page load. If you've ever used a single-page application like Gmail and Google Maps, this is how you're able to go through your inbox and navigate through the map without changing the page you're on.

AJAX stands for Asynchronous JavaScript and XML. Asynchronous code is code that runs in parallel with something else, so in this case, you can request or send data without affecting your browsing experience.

XML

XML, standing for eXtensible Markup Language, is similar to HTML but is used for data transfer, just like JSON. The only problem is that XML is typically heavily, harder to read and doesn't integrate as gracefully as JSON does with JavaScript.

Here's an example of some XML:

XML

<dog> <name>Sophie</name> <age>3</age> <weight>20</weight> </dog>

Because of XML's downsides, AJAX, originally created to be used in conjunction with XML, is now more popularly used with JSON instead.

Making AJAX Calls with Fetch

Instead of making AJAX calls using the original method, via an XMLHttpRequest, we'll be using the more modern fetch instead.

We'll be using JSONPlaceholder as the source of the information, and get their posts. If you were to click here, you'll see the data that we're going to try and fetch.

JAVASCRIPT

const base = 'https://jsonplaceholder.typicode.com'; fetch(base + "/posts").then(response => { response.json().then(json => { console.log(json); }); });

The result of using fetch.

With that data, you can then do whatever it is that you'd like with it. You can add it to the page, perform calculations on it, or pretty much anything.

An important thing to note here is that since this is asynchronous, the request for data will run in parallel with the rest of the code running in your browser, which is a good thing!

Resources

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4