1

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);
isherwood
  • 58,414
  • 16
  • 114
  • 157
thejmazz
  • 48
  • 2
  • 8

1 Answers1

2

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
    }
});
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
  • But why would `$images` be of length 0 after the ajax call? Wouldn't the data stay there after being pushed into the array? – aug Apr 29 '14 at 21:19
  • Okay, so now I'm getting the correct array length added. So does this mean that all my functions that use this filled array need to be called from within the success block? – thejmazz Apr 29 '14 at 21:27
  • Normally yes, but it depends on your needs and on your implementation – Irvin Dominin Apr 29 '14 at 21:30
  • @jmazz If you want have your code isolated (functions/object not dependent on each other too much) you can raise an event inside the `success` function and have all the subscribers notified about new data. Have a look at http://api.jquery.com/trigger/ or https://github.com/rniemeyer/knockout-postbox – SOReader Apr 29 '14 at 21:44