1

At the moment I have integrated Last.fm API on my site www.midnightlisteners.com but it puts all the Last.fm data on the last one Kanye West. If you hover over the ( i ) icon you will see the data comes up in a tool-tip.

I would like to loop through all and add them in the corresponding place. Plus it would be great If someone could help me get the small artist images too.

My jQUery code:

$(document).ready(function() {
      // Find Related Artists based on Last.fm JSON Results
      $(".artist-data").each(function() {
          // Find the artist name in the "p" tag and save it
          artistName = $(this).find(".artist-wrap-mid p");
          artist = artistName.text();
          // Create a class out of the artist name made of lowercase letters and "-" instead of spaces
          artistClass = artist.toLowerCase().replace(/ /g, '-');
          // Add this class to the .artist-data div
          $(this).addClass(artistClass);

          // Check if a value is present
          if (artist === '') {
              $("." + artistClass + " .related").html("No related artist info found for " + artist);
          }
          // Otherwise return the request with links to each related artist
          else {
              $.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=" + artist + "&api_key=9c991c10bf461ac4e4f92fdfa14c20c2&limit=3&format=json&callback=?", function(data) {
                  var html = '';
                  $.each(data.similarartists.artist, function(i, item) {
                      html += "<a href='http://" + item.url + "' target='_blank'>" + item.name + "</a>, ";
                  }); // End each
                  $("." + artistClass + " .related").append(html);
              }); // End getJSON     
          } // End Else
      }); 
});

My HTML is best seen in my website: www.midnightlisteners.com

But it puts all the data from Last.fm in to <div class="related"> </div>

I have gotten a ton of help here: writing.sackettsolutions.com/2012/02/navigating-the-last-fm-api-with-a-little-help-from-jquery-getjson

Pullapooh
  • 161
  • 1
  • 4
  • 14

1 Answers1

3

This is a general problem. It is about loops that contain asynchronous calls with callbacks. The loop will run very fast and will create all of the $.getJSON() calls really fast. By the time the callbacks are running, the loop has finished, so the closure scope of the callback will contain only the reference to the data of the last loop cycle.

Solution: Loosen the loop ... only start the next loop cycle AFTER the previous one has finished its callback. So instead of running a fixed .each() loop, you will have to increment the index inside the callback and start the next loop cycle "manually".

EDIT 2: Your code should be something in the lines of (untested!)

var currIndex = 0;
var $currArtists = $('.artist-data');

if($currArtists.length > 0) getNextArtistInfo();

function getNextArtistInfo() {
    // get reference to current artist
    var $currArtist = $currArtists.eq(currIndex);
    artistName = $currArtist.find(".artist-wrap-mid p");
    artist = artistName.text();
    // Create a class out of the artist name made of lowercase letters and "-" instead of spaces
    artistClass = artist.toLowerCase().replace(/ /g, '-');
    // Add this class to the .artist-data div
    $currArtist.addClass(artistClass);

    // Check if a value is present
    if (artist === '') {
          $("." + artistClass + " .related").html("No related artist info found for " + artist);
          currIndex++;
          if(currIndex < $currArtists.length)
              getNextArtistInfo();
    }
          // Otherwise return the request with links to each related artist
    else {
        $.getJSON("http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=" + artist + "&api_key=9c991c10bf461ac4e4f92fdfa14c20c2&limit=3&format=json&callback=?", function(data) {
            var html = '';
            $.each(data.similarartists.artist, function(i, item) {
                html += "<a href='http://" + item.url + "' target='_blank'>" + item.name + "</a>, ";
            }); // End each
            $("." + artistClass + " .related").append(html);
            currIndex++;
            if(currIndex < $currArtists.length)
                getNextArtistInfo();
        });
    }
}
devnull69
  • 16,402
  • 8
  • 50
  • 61
  • Thanks, Could you maybe help me out with this? I am really new to jQuery. I just started reading jQuery novice to ninja book :D – Pullapooh Sep 04 '12 at 11:25
  • Yess it is working perfectly!! :) thanks so much Devnull. I don't know but if you have time could you maybe help with the artist images? here they are using them but i don't know how to implement it my self on my page. [Link](http://writing.sackettsolutions.com/2012/02/navigating-the-last-fm-api-with-a-little-help-from-jquery-getjson/) – Pullapooh Sep 04 '12 at 13:45
  • what "help with the artist images" do you need?? – devnull69 Sep 04 '12 at 14:21
  • ohh sorry i didn't explain myself. But i got them loaded now :) Thanks again a ton of all your help. – Pullapooh Sep 04 '12 at 15:19
  • i did change: `"" + item.name + ", ";` TO `"
  •  " + item.name + " " + item.name + "
  • ";` It now loads the images too from Last.fm – Pullapooh Sep 04 '12 at 15:42