In a previous post I was refreshing my memory with vanilla JavaScript after years of jQuery-ing, especially AJAX request and the
XMLHttpRequest()
My eyes rolled when I was reading more about it then I found fetch() ( I know its been about since 2015 and now almost universally adopted).
Fetch does what XMLHttpRequest does but in a more elegant way and DOES NOT need additional libraries as it is bundled with JavaScript. It also makes use of “promises” .
const url = "https://randomuser.me/api/?results=10"; fetch(url) .then(function(response) { return response.json(); }) .then(function(data) { console.log(data.results); }) .catch(function() { console.log("Booo"); });
The above code queries the URL, then parses the string as JSON, then does something with the data.
It also catches errors.
Good eh?
Its looks to be easy to expand and do all manner of fetching. For example submitting a form
var form = new FormData(commentForm); fetch( url, { method: "POST", body: form })
You can then chain .then() promises to get the desired outcomes.
For more information
A quick introduction video from Google
From Google Working with the Fetch API
Jake Archibald’s post Thats so Fetch
Scotch post The Fetch API