I have 4 different JQuery AJAX functions, each fetching different information from the last.fm API. This info has to be joined together in a tooltip.
These are my 4 functions:
- Gets the album for a given track & artist. Returns track name.
- Gets the artist image. Returns 1 URL.
- Gets the top 3 albums of the artist. Returns array of 3 strings.
- Gets the #1 top track of a given artist. Returns track name.
var getTrackAlbum = function(track, artist) {
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "track.getInfo",
api_key : settings.LASTFM_APIKEY,
track : track,
artist : artist,
format : "json"
},
function(data) {
return data.track.album.title;
});
}
var getArtistImage = function(artist) {
var options = {
artSize: 'medium',
noart: 'images/noartwork.gif',
}
if(options.artSize == 'small'){imgSize = 0}
if(options.artSize == 'medium'){imgSize = 1}
if(options.artSize == 'large'){imgSize = 2}
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getInfo",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
return stripslashes(data.artist.image[imgSize]['#text']);
});
}
var getArtistTopAlbums = function(artist) {
var albums = new Array();
var onComplete = function() {
return albums;
}
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getTopAlbums",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
$.each(data.topalbums.album, function(i, item){
albums[i] = item.name;
if(i == 2) {
onComplete.call(this);
return;
}
});
});
}
var getArtistTopTrack = function(artist) {
$.getJSON(
settings.PHP_REQUEST_URL,
{
method: "artist.getTopTracks",
api_key : settings.LASTFM_APIKEY,
artist : artist,
format : "json"
},
function(data) {
return data.toptracks.track[0].name;
});
}
I have decided against doing all the requests inside a unique method for reuse purposes. However, now I want to wait for ALL the AJAX requests to complete before I set the HTML of my tooltip.
Here’s the code of my tooltip:
$('.lfm_info').on('mouseover', function(){
var toolTip = $(this).children('.tooltip');
var trackhtml = $(this).parent().children('.lfm_song').html().split(".");
var track = trackhtml[1].trim();
var artist = $(this).parent().children('.lfm_artist').html();
// needs to wait until the AJAX is done!
toolTip.html('html here');
$('#tracks').mouseleave(function(){
if(toolTip.is(':visible')){
toolTip.fadeOut(500);
};
});
toolTip.fadeIn(500);
});
}
How would I wait for all requests to complete before invoking toolTip.html(...)?
Store each request, then use
$.whento create a single deferred object to listen for them all to be complete.