Search code examples
javascriptgiphy-api

Can't loop through Giphy API Array


I have a CodePen utilizing the GIPHY API that calls GIFs based off user input. It works except it only calls the first item in an array. I realize because this is calling the first item in an array. I tried replacing 0 with i and attempted a for loop but it would not make the call. Please note I am using jQuery.

https://codepen.io/anon/pen/wdewjL

HTML

<div class="container-fluid">
  <div class="row">
    <div class="col-sm-12">
      <h1>GIF Search</h1>
    </div>
  </div><!-- END ROW-->

 <div class="row">
   <div class="col-sm-12 outerWrapper">

   <form>
     <input type="text" id="userQuery" value="" placeholder="">
     <br>
     <button class="btn" type="submit" id="searchButton">Search</button>


 <div class="row">
   <div class="col-md-4 col-sm-6">
     <div class="search-text"> 
     </div>

     <div class="img-container">
      <a class="img-link" target="_blank" href="#"><img id="searchResults" src="" /></a>
    </div><!-- END IMG-CONTAINER -->
  </div><!-- END COL -->

</div><!-- END ROW -->
  <a href=giphyURL onclick="redirect" target="_blank">Share</a>


</div><!-- END CONTAINER -->

JAVASCRIPT

$( document ).ready(function(){

// Construct the URL
$('#searchButton').on('click', function(e){
e.preventDefault();

var queryURL= "https://api.giphy.com/v1/gifs/search?q=" + $('#userQuery').val() +  "&api_key=dc6zaTOxFJmzC";

var limit = '&limit=24';
var q = $('#userQuery').val();

// Call API
$.ajax(
{
  type: 'GET',
  url: queryURL, 
  success:function(response){

  // This is the API response data. It's a   JSON object of 24 gifs 
  response.data.forEach(function() {
  var giphyURL = response.data[0].images.fixed_height.url;
  console.log(giphyURL);

  var imageResult = $('<img class=img-result src=' + giphyURL + ' />');
  imageResult.appendTo($('.img-container'));

 });

 $('.search-text').html('<p>Search result for ' + q + '</p>');

 }
});

})


});

Solution

  • Here is the updated codepen https://codepen.io/anon/pen/dWRbaj

    Problem was in the foreach, the item being iterated on is passed in as the argument to the callback function you provide.

    let data = [1,2,3,4];
    data.foreach(function(item){
       console.log(item);
    })