So I'm trying to create a small app for myself using the Last.fm API.
I stuck now on the problem that when I request the Track Duration I can successfully log it into the console and append it from the Dev Tools but in the first run on the DOM itself it just spits out an undefined or NaN (if I use parseFloat) .
Is it possible that my ajax request to slow is, to fetch the data from the API and then also to render it on the DOM? If yes, what would be the possible solution for it? Or a push in the right direction where to look would be sweet.
Here is my jQuery Code:
var Trackster = {};
const API_KEY = '1234';
var trackResults;
var trackDuration;
$(document).ready(function() {
$("#submitButton").click(function() {
Trackster.searchTracksByTitle($("#inputField").val());
$('#detailContainer').empty();
})
})
/*
Given an array of track data, create the HTML for a Bootstrap row for each.
Append each "row" to the container in the body to display all tracks.
*/
Trackster.renderTracks = function(tracks) {
for (var i = 0; i <= (trackResults.length)-1; i++) {
var mediaAlbumArt = trackResults[i].image[1]["#text"];
$.ajax({
url: 'https://ws.audioscrobbler.com/2.0/?
method=track.getInfo&
api_key='+API_KEY+'&artist='
+ trackResults[i].artist
+ '&track='
+ trackResults[i].name
+ '&format=json',
dataType: 'jsonp',
success: function(d) {
console.log("Success", d.track.duration);
trackDuration = d.track.duration;
},
error: function(err) {
console.log("Error", err);
}
})
var $tracks = '<div id="song-details" class="container-fluid">'+
'<div class="row align-items-center h-100">'+
'</div>'+
'<div class="col-md-1">'+
'<span>' + parseFloat(i+1) + '</span>'+
'</div>'+
'<div class="col-md-3">'+
'<span>' + trackResults[i].name + '</span>'+
'</div>'+
'<div class="col-md-2">'+
'<span>' + trackResults[i].artist + '</span>'+
'</div>'+
'<div class="col-md-2">'+
'<img src="' + mediaAlbumArt + '" />'+
'</div>'+
'<div class="col-md-1">'+
'<span>' + trackResults[i].listeners + '</span>'+
'</div>'+
'<div class="col-md-1" id="duration">'+
'<span>' + trackDuration + '</span>'
'</div>'+
'</div>'+
'</div>';
$('#detailContainer').append($tracks);
}
};
Trackster.searchTracksByTitle = function(title) {
$.ajax({
url: 'https://ws.audioscrobbler.com/2.0/?
method=track.search
&track='+($("#inputField").val())
+'&api_key='+API_KEY+'
&format=json',
dataType: 'jsonp',
success: function(data) {
console.log("Success!", data);
trackResults = data.results.trackmatches.track;
Trackster.renderTracks();
},
error: function(e) {
console.log("Error!", e);
}
})
};
I included the ajax request in the loop as I need to know the duration of every song and that's the solution I came up with.
And here is the App running on GitHub https://drood87.github.io/start/
Hope someone can give me a hint or two. Thanks <3