Richard Obaseki
Richard Obaseki

Reputation: 11

Trying to make an AJAX API call

so i'm trying to make an AJAX API call from giphy and I think I have my code laid out correctly but I keep getting undefined as a response. Does anyone know how I may fix this. Thanks in advance guys

var topics = ["Drake", "Nicki Minaj"];

// function to display contents in our HTML
function displayGifContents () {

var gifs= $(this).attr("data-type");
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + gifs + "&api_key=9oQvRPi6s7AzEMcHRHx2Xnc9imoT9oTC";
// Creating an AJAX call for the button being clicked
$.ajax({
    url: queryURL,
    method: "GET"
}).then(function(response) {
    console.log(response);
  var results = response.data;

//   Looping through the data gotten from our api
for (var i = 0; i < results.length; i++) {
      // creating a div to hold the gif image
    var gifDiv = $("<div class='gif-div'>");

    // Storing the rating data
    var rating = results.rating;

    // Creating an element to have the rating displayed
    var p = $("<p>").text("Rating: " + rating);

    gifDiv.append(p);
    $("#dcard").append(gifDiv);
}

Upvotes: 0

Views: 69

Answers (1)

FK82
FK82

Reputation: 5075

I'm unsure what the problem is, but you can take a look at the following code for which the response returns actual ratings:

var topics = ["Drake", "Nicki Minaj"];

const gifDiv = $('.gif-div');
const buttonContainer = $('#button-container');

topics.forEach((topic) => {
  buttonContainer.append(`<button onclick="displayGifContents('${topic}')">GIFs for "${topic}"</button>`);
});

// function to display contents in our HTML
function displayGifContents (topic) {

  var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&api_key=9oQvRPi6s7AzEMcHRHx2Xnc9imoT9oTC";
  
  gifDiv.text('Please wait...');
  
  // Creating an AJAX call for the button being clicked
  $.ajax({
      url: queryURL,
      method: "GET"
  }).then(function(response) {
    console.log(response);
    var results = response.data;

    gifDiv.empty();
    results.forEach(({ rating }) => {
      gifDiv.append(`<p>Rating: ${rating}</p>`);
    });
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button-container">
</div>
<hr/ >
<h2>Ratings</h2>
<div class="gif-div">
</div>

If I had to guess, I would say that you don't construct the request URL correctly. You can debug this e.g. by having a look at the network panel in Chrome developer tools.

Upvotes: 1

Related Questions