Fetch vs Ajax

How to use fetch with async / await in JavaScript. Comparison with Ajax

Fetch is a browser API for loading texts, images, structured data, asynchronously to update an HTML page.

It's a bit like the definition of Ajax! But fetch is built on the Promise object which greatly simplifies the code, especially if used in conjunction with async/await. One could also use promises with the XMLHttpRequest object, but this, added to Ajax's already more complex code would produce a much larger program.

Fetch is compatible with all recent browsers including Edge, but not with Internet Explorer. Therefore, if you are looking for maximum compatibility, you will continue to use Ajax to update a web page. If you also want to interact with the server, the WebSocket object is also more appropriate than fetch. In other cases, fetch offers a great simplicity to load content in a page, as we will see with the following demonstrations.

Loading a text

Fetch loads a resource that is converted to a string with the text () method. Both return a promise, so we use await to wait for the result to be returned.

<fieldset>
<p id="textdemo"></p>
</fieldset>
<script>
var textdemo = document.getElementById('textdemo');
async function loadText(fname) {
var str = await fetch(fname)
textdemo.innerHTML = await str.text()
}
loadText("demotext.txt")
</script>

Loading an image

In the case of an image, fetch returns a blob with the blob () method. While the img tag requires a URL to be assigned to the src attribute. We therefore convert the content obtained by fetch into URL with the createObjectURL method of URL.

<fieldset>
<img id="imgdemo" />
</fieldset>
<script>
var imgdemo = document.getElementById('imgdemo');
async function loadImage(fname) {
var response = await fetch(fname)
imgdemo.src = URL.createObjectURL( await response.blob() )
}
loadImage("images/angry-birds.jpg")
</script>

Loading a JSON file

A JSON file is loaded as a resource by fetch and parsed into a JavaScript object with the json () method. You can then access the values of the attributes of the object by name.

<fieldset>
<p>Name <input type="text" id="jsondemo1" value="" /></p>
<p>Year <input type="text" id="jsondemo2" value="" /></p>
</fieldset>
<script>
async function loadJSON(fname) {
var response = await fetch(fname)
var j = await response.json()
document.getElementById('jsondemo1').value = j.name
document.getElementById('jsondemo2').value = j.year
}
loadJSON("demojson.json")
</script>

Name

Year

Adding controls

It is also possible to catch the possibility that the resource is not accessible on the server. Even though there are different ways to control the return of fetch, the simplest is a try catch.

<fieldset>
<p id="ctrldemo"></p>
</fieldset>
<script>
var ctrldemo = document.getElementById('ctrldemo')
async function loadCTRL(fname) {
try {
var response = await fetch(fname)
var j = await response.json()
ctrldemo.innerHTML = JSON.stringify(j)
}
catch(err) {
ctrldemo.innerHTML = "Error, can't load " + fname + " " + err
}
}
loadCTRL("demojson.json")
</script>

Example when the file is found:

Example when the file does not exist:

See also ...

© July 13, 2017 Xul.fr