mh108
8/13/2019 - 3:03 PM

Flickr API request with jQuery.ajax() method for CORS request

// jshint esversion: 8
// Important: update all http:// schemas to https://

let jsonFlickrFeed = response => {
  //test: extract an image from the response
  //console.log(response.items[0].media.m);
  response.items.forEach(function(item, index) {
    //Flickr returns 20 images by default
    //We need only six images for the Gallery
    if (index < 6) {
      // create a new JQuery element to hold the image
      // but hide it so we can fade it in
      let $img = $("<img>").hide();

      // set the attribute to the url
      // contained in the response
      $img.attr("src", item.media.m);
      $img.attr("width", "115");

      // attach the img tag to the main
      // photos element and then fade it in
      $(".photos").append($img);
      $img.fadeIn();
    } //if
  }); //foreach
}; //jsonFlickrFeed

let clickHandler = function() {
  //get tag entered by user
  let tagVal = $("input").val();
  //insert the tag into the URL
  let requestURL =
    "https://api.flickr.com/services/feeds/photos_public.gne?tags=" +
    tagVal +
    "&format=json&callback=jsonFlickrFeed";
  console.log(requestURL);
  $(".b").html(""); //clear box b
  //$.getJSON(requestURL, function(response) {
  $.ajax({
    dataType: "jsonp",
    url: requestURL,
    crossDomain: true,
    jsonp: "jsonFlickrFeed"
  });
  //.done();
};

$(document).ready(() => {
  $("button").on("click", clickHandler);
  $("input[type=text]").on("keypress", () => {
    //return key pressed?
    if (event.keyCode === 13) {
      clickHandler();
    }
  });
});