How to wait until getJSON has gotten all records in jQuery

577 views Asked by At

I have this script where I pull through photos from Flickr using jQuery. I'm using the zFlickrFeed script. I need to pull through 300 images from Flickr but currently I'm getting 20 pulled through. I think this is because my getJSON method is interrupted before it is finished.

How do I wait until all 300 have gone and then call my conditional methods? The methods in the condition essentially render the JSON data into either a grid or list style layout.

(function($){
$.fn.flickrfeed = function(userid, tags, options) { 

    // Set plugin defaults
    var defaults = {
        limit: 300,
        header: true,
        layout: 'list',
        imagesize: 'small',
        titletag: 'h4',
        title: true,
        description: true,
        date: true
    };  

    var options = $.extend(defaults, options); 

    // Functions
    return this.each(function(i, e) {
        var $e = $(e);

        // Add feed class to user div
        if (!$e.hasClass('flickrFeed')) $e.addClass('flickrFeed');

        // Define Flickr feed API address
        var api = 'http://api.flickr.com/services/feeds/photos_public.gne?lang=en-us&format=json&jsoncallback=?';
        if (userid != '') api += '&id=' + userid;
        if (tags != '') api += '&tags=' + tags;

        // Send request
        $.getJSON(api, function(data) {
            // Process the feeds
            if(options.layout == 'list') {
                _callback(e, data, options);
            }
            else if(options.layout == 'grid') {
                _altcallback(e, data, options);
            }
        });             
    });
};
2

There are 2 answers

0
bugkiller On

I would create a counter and once it hits the required number of calls, i'd hit the success function.

i'd add: var counter = this.length and in the $.getJSON success function, i'd add: if (--counter > 0) return; this is the code:

var counter = this.length;
return this.each(function(i, e) {`

    var $e = $(e);

    // Add feed class to user div
    if (!$e.hasClass('flickrFeed')) $e.addClass('flickrFeed');

    // Define Flickr feed API address
    var api = 'http://api.flickr.com/services/feeds/photos_public.gne?lang=en-us&format=json&jsoncallback=?';
    if (userid != '') api += '&id=' + userid;
    if (tags != '') api += '&tags=' + tags;

    // Send request
    $.getJSON(api, function(data) {
        if (--counter > 0) return;
        // Process the feeds
        if(options.layout == 'list') {
            _callback(e, data, options);
        }
        else if(options.layout == 'grid') {
            _altcallback(e, data, options);
        }
    });             

    });
0
Sarath Chandra On

Did you try rewriting the getJSON to the full-fledged $.ajax call and then use a .done() or success function call ?

$.ajax({ url: api }).done(function(data) { // Process the feeds });

OR

$.ajax({ url: api success: function(data) { // Process the feeds } });