Domanda

I'm trying to append the link value of Instagram images into an array. The link values are showing up fine in the console but my array length is 0 after the ajax function. Also '0' shows up in the console before all the links.

I have an idea this problem is caused by ajax running asynchronously and so the rest of the js code is actually run before anything can be appended to $images, but I have no idea how to circumvent this. This is my code:

$liked = 'https://api.instagram.com/v1/users/self/media/liked?access_token=' + $access_token + '&COUNT=20';
$images = []

$.ajax({
    type:'get',
    dataType:'jsonp',
    cache: false,
    url: $liked,
    success: function(data) {
        for (var i = 0; i < data.data.length; i++) {
            console.log(data.data[i].images.standard_resolution.url);
            $images.push(data.data[i].images.standard_resolution.url);
        }

    }
});
console.log($images.length);
È stato utile?

Soluzione

The console.log will run before the ajax call is ended; write your code or you console.log in your success function right after the end of the data loop.

Like:

$liked = 'https://api.instagram.com/v1/users/self/media/liked?access_token=' + $access_token + '&COUNT=20';
$images = []

$.ajax({
    type:'get',
    dataType:'jsonp',
    cache: false,
    url: $liked,
    success: function(data) {
        for (var i = 0; i < data.data.length; i++) {
            console.log(data.data[i].images.standard_resolution.url);
            $images.push(data.data[i].images.standard_resolution.url);
        }
        console.log($images.length); // here the array is filled with response data
    }
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top