Skip to content

Instantly share code, notes, and snippets.

@phette23
Created February 19, 2012 22:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save phette23/1866234 to your computer and use it in GitHub Desktop.
Save phette23/1866234 to your computer and use it in GitHub Desktop.
Last.fm Recent Tracks API
<h3>Last.fm Scrobbles</h3>
<!-- div below will be filled in with formatted contents of API response -->
<div id="recent-tracks" style="display:none;"><a href="http://last.fm/">Last.fm</a> data hasn't loaded yet.</div>
<!-- leave as display:none for the fade in effect -->
(function($){ //put everything in a wrapper to ensure jQuery's use of $ doesn't conflict with other libraries
//see http://www.last.fm/api/show/user.getRecentTracks for API documentation
//there are more optional parameters such as to, from, & page that this example doesn't use
var user = "username"
var apiKey = "your API key"
//using jQuery's GET method for ajax
$.get("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=5&user=" + user + "&api_key=" + apiKey,
function(response){ //callback function, runs upon receiving response
var output = '<ul style="list-style-type:none">';
$(response).find('track').each(function(){
var trackURL = $(this).find('url').text(); //url for the specific track
var trackName = $(this).find('name').text(); //name of the track
var artist = $(this).find('artist').text(); //artist
var date = $(this).find('date').text(); //date & time played
var trackFinal = "<li>";
if (date) {
trackFinal += date + " - ";
}
else {
trackFinal += "Now playing: "; //currently-playing songs have no date
};
trackFinal += " <a href='" + trackURL + "'>" + trackName + "<\/a> by <a href='http://www.last.fm/music/";
trackFinal += encodeURIComponent(artist) //artist names may have special characters e.g. Why?
trackFinal += "'>" + artist + "<\/a><\/li>";
output += trackFinal;
});
output += "</ul>";
$('#recent-tracks').html(output).fadeIn('slow'); //nice fade in effect
},
"xml"); //expecting XML as a response, could leave this blank
}(jQuery)); //execute wrapper function with $ = jQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment