JavaScript AJAX Basics (retiring) AJAX and APIs Making the AJAX Request

Félix Guérin
Félix Guérin
17,910 Points

Making this request in ES6 (with Fetch API)

I'm trying to rewrite this request using ES6 features and the Fetch API. My problem is with the 2nd parameter of the $.getJSON method, where we create an object to be sent with the request so we can ask for specific properties (tags, format, etc.). I haven't been able to find anything resembling that with the Fetch API.

I have this so far:

const button = document.querySelectorAll('button');
button.forEach((e) => {
  e.addEventListener('click', function (event) {
    button.forEach((e) => {e.classList.remove("selected")});
    (event.target).classList.add("selected");
    const flickrAPI = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?';
    let animal = (event.target).textContent();
    let options = {
    tags: animal,
    format: "json"
    };
    function displayPhotos(data) {

    }
    fetch(flickrAPI)
      .then((response) => response.json)
      // HOW DO I USE THE 'OPTIONS' VARIABLE CREATED ABOVE
      .then((data) displayPhotos(data){
      // Function to be written in the next video
    }); // End displayPhotos      
  }); // End event handler
}); // End forEach

2 Answers

Brendan Whiting
MOD
Brendan Whiting
Front End Web Development Treehouse Moderator 84,129 Points

I’m looking at the docs here. It looks like the second parameter is an object or string (object in our case) that’s appended to the URL as a query string.

According to this StackOverflow answer, a good way of adding query params to the url is to build them using the URL and URLSearchParams objects.

There's a video in a Treehouse course on HTTP Basics that might be a good refresher.

Tobiasz Gala
Tobiasz Gala
Full Stack JavaScript Techdegree Student 21,800 Points

I see that you are using flickr public API. There are parameters you can enter to retrieve data. I think you know what to do :)

https://api.flickr.com/services/feeds/photos_public.gne?tags=animal&format=json