JQuery Combining Ajax Objects from APIs
I have 2 problems. My ultimate goal is to query Instagram and filter images by tag. Instagram doesn't allow more than 33 images at a time, so right now I have ajax inside another. The first request gets the images and then checks if there is more, if there is more, I make another request. So here are my 2 problems.
# 1 . I cannot combine these 2 objects into 1. I have tried everything I could think of or find on the internet.
var new_data = $.extend({}, data, data2);
and
$.extend(data, data2);
don't work, it just gives me 1 object back
# 2 . My logic below is a little flawed because it will allow me to get a maximum of 66 images (2 requests, 33 images each). I really need to have ajax in some kind of loop. But I don't know how to do it.
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 an example of what I get from Instagram
source to share
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();
}
}
});
}
})
source to share
If you are trying to match the elements of two arrays you are using it $.extend
wrong.
# 1 To copy the contents of an array, you use a function Array.prototype.concat
. Example:
var new_data = data.concat(data2);
Note: $.extend
Used to combine content. See http://api.jquery.com/jquery.extend/ .
# 2 . Instagram contains the pagination key in all of its responses. You can use this in your callback to trigger another ajax request. See pagination at https://instagram.com/developer/endpoints/
Note. Speed ββlimits apply: 5000 or hour per token for authenticated calls. See https://instagram.com/developer/limits/
source to share