Search code examples
jqueryajaxinstagraminstagram-api

jQuery Combine Ajax Objects From Instagram API


I have 2 problems. My ultimate goal is to make a request to Instagram and filter the images by tag. Instagram doesn't allow for more than 33 images at a time so right now I have an ajax inside of another. The first request gets images and then checks if there are more, if there are more I make another request. So here are my 2 problems.

#1 - I can't combine these 2 objects into 1. I have tried everything I could think of or find online.

var new_data = $.extend({}, data, data2);

and

$.extend(data, data2);

are not working, it just gives me 1 of the objects back

#2 - My logic below is somewhat flawed, because this would only allow me to get 66 images max (2 request, 33 images each). What I really need is to have the ajax in a loop of some sort. But I'm not sure how to do that.

var userid = '#######';
var token = '############';
var url = 'https://api.instagram.com/v1/users/' + userid + '/media/recent/?access_token=' + token + '&count=33';

$.ajax({
    type: 'GET',
    dataType: 'jsonp',
    cache: false,
    url: url,

    success: function(response){
        var paging = response.pagination;
        var data = response.data;
        console.log(data);

        if(paging.hasOwnProperty('next_url')){

            url = paging.next_url;

            $.ajax({
                type: 'GET',
                dataType: 'jsonp',
                cache: false,
                url: url,
                success: function(response2){
                    var data2 = response2.data;
                    var new_data = $.extend({}, data, data2);
                }
            });

        }else{
            // No more images so create image gallery
        }
    },
    error: function(){
        // error stuff
    }
});

Here is sample of what I am getting back from Instagram

enter image description here


Solution

  • Tested. It works. Try

    var imageData = [];
    $(function() {
        var url = 'https://api.instagram.com/v1/tags/smpspree/media/recent/?client_id=81e3d3f35c8a4438964001decaa5a31f&count=11'; 
    
        getData(url, function() {
            for (var i in imageData) {
                console.log(imageData[i])
            }
        }); 
    
        function getData(url, callback){ 
            $.ajax({ 
                type: 'GET', 
                dataType: 'jsonp', 
                cache: false, 
                url: url, 
                success: function(response){ 
                    console.log(response.data)
                    imageData = imageData.concat(response.data)
                    var paging = response.pagination; 
                    if (paging.hasOwnProperty('next_url')) { 
                        getData(paging.next_url, callback) 
                    } else {
                        callback.call();
                    } 
                } 
            }); 
        }
    
    })