0

I'm using the iTunes API to gather information. To keep my code modular as far as tasks needed, I have my code setup similar to what's presented here. Adding onto this code I'd like to insert the information from the JSON into the DOM using a click event. The problem is that I'm getting undefined whenever the click event is fired despite being able to successfully retrieve the JSON. Why is this so? More importantly is there a better approach to create functions from JSON get requests then what I have now?

$(function() {
  $("button").on("click", function() {
    var artistName = iTunesSearch(albumInfo);
    $(".artist-name").text(artistName);
  });
  
  function iTunesSearch(callback) {
    $.getJSON("http://itunes.apple.com/search?term=College Dropout&entity=album&callback=?", function(data) {
      var result = data['results'][0];
      callback(result);
    });
  }
  
  function albumInfo(data) {
    console.log(data["artistName"]); // Successfully logs info just doesn't return the data 
    return data["artistName"];
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Generate Info</button>
<p><b>Artist Name:</b> <span class="artist-name"></span></p>
Community
  • 1
  • 1
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
  • Use a callback that does the work to update the DOM. That way, it will run after the asynchronous operation completes. – Pointy Apr 12 '15 at 14:53
  • So would that require changing `$.getJSON` to `$.ajax`? – Carl Edwards Apr 12 '15 at 14:56
  • No, the basics are the same with any sort of asynchronous operation. The key is to stop thinking in terms of return values and start using callback functions. You've got a callback already, but it's not taken over all the responsibilities for dealing with the completed lookup operation. That's where the DOM modification should go. – Pointy Apr 12 '15 at 14:59

0 Answers0