In this post we’ll do everything we did in the second post, but with Fetch API.

What’s this Fetch API?

The almighty docs say

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest but the new API provides a more powerful and flexible feature set.

I prepared this demo page so that you can test.

You’ll remember from the last post that in order to make an AJAX call with jQuery, you have to do something like this:

$('#result').load('http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');

Go ahead and run that code on the demo page in the browser’s dev tools Console

Now, the very same thing with the Fetch API looks like this:

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
fetch(link)
    .then(function(response){
        return response.json()
    })
    .then(function(result){
        var oglasiHTML = '';
        $.each(result, function(index, oglas){
            var klasaCijene = '';
            if (oglas.cijena < 100){
                klasaCijene = 'is-success';
            }
            else if (oglas.cijena >= 100 && oglas.cijena < 300){
                klasaCijene = 'is-info';
            }
            else if (oglas.cijena >= 300){
                klasaCijene = 'is-danger';
            }
 
            oglasiHTML += `
                <div class="columns">
                    <div class="column is-one-quarter">
                        <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                    </div>
                    <div class="column">${oglas.tekst}</div>
                </div>
            `;
        });
 
        $('#oglasi').html(oglasiHTML);
    });

Go ahead and try it in the Console. Change the ime parameter, and you’ll see that the text on the page will change to Hello [name], where [name] will be the parameter you entered. Note that in the example above I still used jQuery to set the content of the div with id result.

The docs have way more info on this but, as they say, the difference between fetch() and $.ajax() is in two main things:

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  • By default, fetch() won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

⚠️ At a later point you may want to read a bit more about Promises in Javascript.

Rewriting the mini project

I encourage you to try it for yourself and then check your solution to mine.

The mini project (which you can test here) would be rewritten like this:

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
fetch(link)
    .then(function(response){
        return response.json()
    })
    .then(function(result){
        var oglasiHTML = '';
        $.each(result, function(index, oglas){
            var klasaCijene = '';
            if (oglas.cijena < 100){
                klasaCijene = 'is-success';
            }
            else if (oglas.cijena >= 100 && oglas.cijena < 300){
                klasaCijene = 'is-info';
            }
            else if (oglas.cijena >= 300){
                klasaCijene = 'is-danger';
            }
 
            oglasiHTML += `
                <div class="columns">
                    <div class="column is-one-quarter">
                        <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                    </div>
                    <div class="column">${oglas.tekst}</div>
                </div>
            `;
        });
 
        $('#oglasi').html(oglasiHTML);
    });

There are a few things that I’d like to point out here:

  • I used the response.json() because I know that this API returns a JSON response (you can check by opening that link in the browser).
  • I used the jQuery each function to iterate over the result.
  • I used the template literals to construct the final oglasiHTML in a much cleaner way than we did that in the previous post with using concatenation.

#javascript #api #fetch #ajax

Making AJAX Calls using the Fetch API
2.20 GEEK