0

I'm creating a small music suggestion website using the LastFM API. I've succesfully set up the search function, where people can enter an artist they like and get back one that is similar (using this http://www.last.fm/api/show/artist.getSimilar).

   function getSimilar(){
  var search = $('#search').val();

  var url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist=' + search +'&api_key=ac83636465b06e3626587c01f7d85bba&format=json';


  $.get(url, function(response){
    var similar = response.similarartists.artist[0].name;
    var image = response.similarartists.artist[0].image[2]['#text'];



    $('#result').html(similar);
    $('#result2').html("<img src='"+image+"'>");


  })
};





// Run function on click
$('#submit').click(getSimilar);

However, I also want to include a summary of the artist alongside the name (http://www.last.fm/api/show/artist.getInfo). The actual API call seems to be working... when I enter an artist name in the url where +similar+ currently is it loads the summary for that artist, but of course I want the bio for the artist that actually comes up for the user! Here is the code:

// Get info

function getInfo(){

  var infourl = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist='+ similar +'&api_key=ac83636465b06e3626587c01f7d85bba&format=json'

  $.get(infourl, function(response){
    var info = response.artist.bio.summary;


   $('#result3').html(info);


  })
};

//Run function on click
$('#submit').click(getInfo); 

I'm still learning about APIs and JQuery, so I would be extremely grateful for any guidance on where I have gone wrong. Thank you :)

  • I don't see `similar` being passed into the `getInfo()` method. It looks like you are binding both of the functions to the click of the submit, however one of them needs information returned from the first ajax call. The second method should be called from the success of the first ajax call, not bound to the click itself. – Taplar Nov 25 '16 at 21:44
  • Thanks for the reply! What do you mean by being passed into the getInfo() method? – Ellie C Nov 25 '16 at 22:36
  • `similar` is defined inside the callback for the get in `getSimilar`. It will not exist until get resolves and will only exist inside that callback. `getInfo` is trying to use a `similar` in the url construction. I assume you are intending to use the similar from the first ajax results. Due to the asynchronous aspect of get and the small scope of `similar`, it seems to make more sense to call getInfo from within the function where similar exists, passing it to getInfo so it will be available to it once the get has resolved. – Taplar Nov 25 '16 at 22:50

0 Answers0