I need to make a number of calls to the YouTube API via AJAX to retrieve retrieve video information in JSON format.
Each of the calls can be processed synchronously but once all of the data has been recieved it needs to be processed\displayed.
How can I ensure the processing function is not called before all the data has been received? My current solution has been to call the AJAX function recurssively but I feel like there's a much better solution.
Any help would be much aprreciated.
var categoryWrapper,categories;
var catCnt=0;
function initialiseVideoLibrary() {
categories=new Array("health","hiv","education","volunteering");
getYouTubeData();
}
function getYouTubeData() {
ytJsonUrl = "https://gdata.youtube.com/feeds/api/users/vsomediauk/uploads/-/" + categories[catCnt] + "?v=2&alt=jsonc&max-results=5&orderby=relevance";
$.ajax({
type: "GET",
url: ytJsonUrl,
cache: false,
dataType:'jsonp',
success: function(ytJsonResponse){
if (catCnt < categories.length) {
showCategory(categories[catCnt],ytJsonResponse);
getYouTubeData();
catCnt++;
} else {
tabVideos();
}
}
});
}
function showCategory(cat,ytResponse) {
categoryWrapper = $('<div></div>').addClass('category');
$(categoryWrapper).append($('<h3></h3>').text(cat));
contentDiv = $('<div></div>').addClass('content');
$.each(ytResponse.data.items,function(i,video) {
videoWrapper = $('<div></div>').addClass('video');
$(videoWrapper).append($('<p></p>').text(video.id));
$(videoWrapper).append($('<p></p>').text(video.title));
$(videoWrapper).append($('<img></img>').attr('src',video.thumbnail.sqDefault));
$(contentDiv).append(videoWrapper);
});
$(categoryWrapper).append(contentDiv);
$("#videolist").append(categoryWrapper);
}
function tabVideos() {
$("#videolist").tabulation({tabAlignment : "right", titleTag : "h3", tabPosition : "top"});
}