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!