1
votes

I'm new to JS and trying to get my last.fm toptracks over the last 7 days with a limit of 3 from their API here:

http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=3&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json

Here's my code below which works but whenever I change the limit to more than 1, it fails with no console error. Any idea how I can use .html to print out an array of those 3 track names?

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=1&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json", function(result){
    $.each(result, function(){
        $('#lastfm_toptracks').html(result.toptracks.track.name);
    });
});
3

3 Answers

2
votes

Firstly, you need to amend your code to loop over the returned result.toptracks.track array. Secondly, you need to change html() to append(), otherwise you are overwriting the text of the element on every iteration and will only see the final track. Try this:

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=3&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json", function(result){
    $.each(result.toptracks.track, function(i, track){
        $('#lastfm_toptracks').append('<p>' + track.name + '</p>');
    });
});

Example fiddle

Also, note that the documentation states that the default setting for limit is 50 per request.

0
votes

Below the the code:

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=3&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json", function(result){        
    $.each(result.toptracks.track, function(key, val){        
        console.log(val.name);
        $('#lastfm_toptracks').append('<div>'+ val.name + '</div>');
    });
});

And the fiddle:

http://jsfiddle.net/k6g6v0rc/1/

0
votes

This is just a Syntax error

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=3&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json", function(results){
console.log(results);
$.each(results.toptracks.track, function(index,value){
    //$('#lastfm_toptracks').html(result.toptracks.track.name);
    alert(value.name);
});

});

Should be working.

The link is to a working demo.

http://jsfiddle.net/nnyf0n28/7/

Please explore more on this link:: http://api.jquery.com/jquery.each/