Api for loop problem

Hi there!

Some time ago I was asked to make a very basic and simple cat-gif app where you push a button and an ajax call is executed resulting in appending random cat gif to a div. I made the call and used for loop to go through JSON data but it always results in appending the last element of the array (i.e in 15 objects array it appends number 15). Manually inserting array object’s number instead of [i] gives a positive result (not random though). So my feeling is that I did something wrong with my for loop.

$(document).ready(function(){
  $('button').on('click', function(){
// API's url 
    var url = 'https://api.giphy.com/v1/gifs/search?q=cat&api_key=c3839c06e9714ed688ffc1a6d5cb14a7&limit=15';
// ajax call
    $.ajax({
      url: url, method: 'GET'
    }).done(function(succ){
// Variable for my convenience. In JSON API's callback there is an array called "data" which stems into various objects
      var out = succ.data;
// for loop searching through the array and inserting the result into div with "foto" id
      for (var i=0; i<out.length; i++){
         $('#foto').attr('src', out[i].images.fixed_height.url); 
      }
    });
    return false;
  });
});

Thanks for your time!

iIf I’m understanding this right - instead of a for loop there, you should just generate a random number and use it to get the image from your data.

var randomNumber = get a random number in the range you want
out[randomNumber].images.fixed_height.url

something like that maybe?

1 Like

Oh, right! Didn’t thought about using Math.random for getting the results. It works fine now but have to tinker to out the repetition problem.Thanks!:wink:

Thank you very much!