I'm working on a new project in my JavaScript course building a "Dog Therapy" page where you click on a button and get a new image from https://dog.ceo/dog-api/

Here is a snippet of the project where we answer the question:

"How do we make an AJAX request from our program to get access to JSON data to display on our page?"

The fetch() method will allow us to do this. Before we look at the fetch() method let's take a brief look at two alternatives. There is the XMLHttpRequest and jQuery.ajax() approach.

If you take a look at the XMLHttpRequest documentation you will see that this can be a bit of a steep learning curve. I found this to make AJAX requests very unapproachable for me the first time I tried to learn AJAX requests. However, over time you may find some benefits of this approach and want to circle back.

I'm just glad we do not have to take this approach in learning to make AJAX requests for the first time.

The next approach comes from the very user friendly jQuery library. jQuery.ajax(). It significantly lowers the barrier to entry. But it requires using the jQuery library so we won't address it at this time.

The great news is that vanilla JS, what we all have access to without any special libraries, gives us the very user friendly fetch() method.

This is our goal:

  • We want to hit the endpoint: "https://dog.ceo/api/breeds/image/random"
  • We want to get back this JSON (the message value will vary each time):
    {
        "message": "https://images.dog.ceo/breeds/coonhound/n02089078_4065.jpg",
        "status": "success"
    }
    	

First, I'll show you the code it takes to pull this off then we'll walk through it step by step:

fetch('https://dog.ceo/api/breeds/image/random')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
   // do something with our JSON data;
  });

The most straightforward use of the fetch() method accepts one argument, the resource path you want to fetch, which returns a promise containing a Response object. Let's take a look at this in the console:

This response is not the actual JSON we want. It is just the HTTP response. We will need to use the json() method to extract the JSON body content from the response. We'll also need another tool to help us when our promise is resolved or rejected, then(). This method takes two functions as parameters.

  1. First function is executed if promise is resolved and a result is received. - We will act on this in our next step.
  2. Second function is executed if promise is rejected and an error is received. - We will skip over implementing this for now.

Awesome! We have successfuly made an AJAX request with the fetch() method. We have access to the message and status values from the JSON object.