2

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"});
    }

4 Answers 4

2

This would be an excellent use of jQuery.Deferred.

Simply store the return values of the calls to jQuery.ajax and then pass them to jQuery.when.

Edit: as I just noticed it isn't obvious from the documentation, I thought I'd note tht you can pass an array of deferreds to when using the following syntax:

$.when.apply(null, ajaxReturnValueArray).then(function() {
    tabVideos(); // Assuming this is the method you wanted to call
});
0

I'm not sure but you can try with the following change :

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,
        async: false,
        dataType:'jsonp',
        success: function(ytJsonResponse){
            if (catCnt < categories.length) {
            showCategory(categories[catCnt],ytJsonResponse);
                getYouTubeData();
                catCnt++;
            } else {
                tabVideos();
            }
        }

    });
}
0

Check out .ajaxStop(), something like this might work (sorry, untested!)

var categoryWrapper,categories;

function initialiseVideoLibrary() {
    categories=new Array("health","hiv","education","volunteering");
    getYouTubeData();
}

function getYouTubeData() {

        $.each(categories, function(index, value) {
            ytJsonUrl = "https://gdata.youtube.com/feeds/api/users/vsomediauk/uploads/-/" + value + "?v=2&alt=jsonc&max-results=5&orderby=relevance";

            $.ajax({
                type: "GET",
                url: ytJsonUrl,
                cache: false,
                dataType:'jsonp',
                success: function(ytJsonResponse){
                    showCategory(value,ytJsonResponse);
                }

            });
        });
}

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);
}

$("#videolist").ajaxStop(function() {
    $(this).tabulation({tabAlignment : "right", titleTag : "h3", tabPosition : "top"});
});
0

I think that the most clean way would be to have the ajax call to be synchronous and then call the getYouTubeData() sequentially in a for loop.

The getYouTubeData() should be:

function getYouTubeData(cat) {

    ytJsonUrl = "https://gdata.youtube.com/feeds/api/users/vsomediauk/uploads/-/" +cat+ "?v=2&alt=jsonc&max-results=5&orderby=relevance";

    $.ajax({
        type: "GET",
        url: ytJsonUrl,
        cache: false,
        async: false, //this is to make tha ajax call synchronous
        dataType:'jsonp',
        success: function(ytJsonResponse){
            showCategory(cat,ytJsonResponse);
        }
    });
}

And you could invoke it like:

for (var iC = 0; iC < categories.length; iC++){
    getYouTubeData(categories[iC]);
}
tabVideos();

This way the tabVideos() will be invoked after all calls to getYouTubeData() have finished.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.