Reputation: 85
I've read lots of questions about asynchronous function here on Stackoverflow and how to return values but I'm not capable of apply those hints on my projects. So I ask for your help for that.
I'm using the iTunes search API to find songs in the store and then add them to a "playlist". The project is developed in JQuery.
Basically, there is a search box called "iTunesSearch" in which I write the name of the song, then a button called "search" that, when clicked, executes the code for retrieve the song in the iTunes store. What I want to do is take the song's name, put in into an array, show it into a div on the page and then search for other songs and repeat the process over and over again. At the end, I would like to have an array which contains all the songs that I've searched.
Here's the code:
$(document).ready(function() {
$('#search').click(function(){
var media = "music";
var limitOfSearchResults = 1;
var thing = document.getElementById('itunesSearch').value;
var whatosearch = $('#itunesSearch').attr('value');
$.getJSON("http://itunes.apple.com/search?term=" + thing
+ "&country=us&limit=" + limitOfSearchResults
+ "&media=" + media
+ "&callback=?",function(data) {
songname = data["results"][0].trackName;
resultPlaylist = createPlaylist(song);
alert(resultPlaylist); //is always 1, it doesn't add songs when I repeat search
});
function createPlaylist(song){
var playlist = new Array ();
playlist.push(song);
return playlist.length; //to test if the array stores the results
)};
});
And here the HTML body snippet:
<input id="itunesSearch" type="text" placeholder="Search for a song..">
<div id="resultiTunes"></div>
<input id="search" type= "button" value="Find!">
How can I pass the songname variable outside the callback and use it to store the name of the song in an array or whatever? I've understood that the problem is that the callback is executed later. I've tried calling a function inside the callback but it won't stack the songs in the array (I've not included the piece of code for this due to its fail). Any ideas?
Thanks in advance.
Upvotes: 3
Views: 1684
Reputation: 85
Resolved. I put the getJSON request into a function and set the return. Then, called the .done() state to use the results:
function foo(){ return $.getJSON("http://itunes.apple.com/search?media=music&term=2&country=it&limit=60&attribute=genreIndex&entity=song&callback=?",function(data) {
//stub
}
)}
foo().done(function(result){
//do something with result})
Upvotes: 3