-1

I've read around 20 question on this specific question but couldn't get any of them to work.

I'm creating a simple jquery function to query the iTunes api to get song data.

I can't seem to get the data outside of the ajax function. I tried with callbacks and async false but nothing seems to work.

here is my code:

function itunesData(artist,song) {
    /* https://itunes.apple.com/search?term=jack+johnson+I+Got+You&entity=song */

        $.ajax({
            type: 'GET',
            url: 'https://itunes.apple.com/search',
            data: { term: artist+' '+song, entity: 'song' },
            dataType: 'jsonp',
            cache: true,
            statusCode: {
                404: function() {
                    alert('are you online?')
                }, 
            },
            success: function( resp ) {
                    if (resp.resultCount == 0) {
                        return false;
                    }
                    if (resp.results[0]) {
                        songDetails = resp.results[0];

                        songArt = songDetails.artworkUrl30;
                        songPreview = songDetails.previewUrl;
                        songUrl = songDetails.trackViewUrl;

                        return itunesData = new Array( songArt, songPreview, songUrl );

                    } 

            },
        });
}

At the end i just need:

var songData = itunesData('Jack Johnson', 'I Got You');

Can you tell me what am I doing wrong?

10x

Sir Code-A-lot
  • 153
  • 1
  • 15
  • Short answer: You don't *return* from the callback (in this case the `success` handler), that return doesn't go anywhere. You *modify state* in the callback. So instead of returning the data, set the data to wherever you need it. (A shared scope variable, page elements, etc.) – David Jul 03 '14 at 10:32
  • 1
    AJAX works the same with PHP too. And while I don't know if PHP has mechanisms for server-side asynchronous functionality, the structures would still be very similar. An async callback isn't on the same call stack as the main thread, so there's nothing waiting for a return value. – David Jul 03 '14 at 10:39

1 Answers1

1

The AJAX call you make is asynchronous; therefore you will need to implement a callback function, separate to itunesData(), to handle the response.

athms
  • 948
  • 5
  • 8