Api for loop problem

Api for loop problem
0

#1

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!


#2

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?


#3

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:


#5

I was playing around with the giphy api and noticed they have another endpoint called random, where you can specify a tag and it will only return one random image. You could avoid the whole random number generation if you went this route.

$(document).ready(function(){
  $('button').on('click', function(){
// API's url 
    var url = 'https://api.giphy.com/v1/gifs/random?tag=cat&api_key=c3839c06e9714ed688ffc1a6d5cb14a7';
// 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
      $('#foto').attr('src', succ.data.image_url); 
    });
    return false;
  });
});

#6

Thank you very much!