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>