Lesson 106: iTunes Search

Estimated Length: 30min | Difficulty: Advanced

In this lesson, we will be going over how to create an iTunes music search using jQuery.

You should be able to search an artist and then find an album or song from that artist to play. By clicking on the song, the user should be able to access a clip to listen to. This can be a great feature to add to a website.

Try it out:

Search For Your Favorite Artist on iTunes!

HTML

The HTML part of this activity is primarily just creating a form from which the user can search from. A basic search bar with button will work.

<!--Search-->

<h1>Search For Your Favorite Artist on iTunes!</h1>

<p>

<label for="search" id="title">Search:</label>

<input type="text" name="search" id="search" placeholder="Search for your favorite artist"/>

<input type="button" id="submit" value="Search Now"/>

</p>

CSS

There is no CSS needed to complete this lesson

jQuery

In order to achieve this lesson, we are going to need to use a lot of advanced jQuery code, and some AJAX code as well. Be sure to read the comments to better understand what the code is doing.

Here is what you need:

<script>

$(document).ready(function(){ //document is ready

$('#submit').click(function(){ //add click function to selected element

var searchterm = $('#search').val(); //set variable of search

//val is the information entered into the search field

$('#results').children().remove(); //removes the children in results

$.ajax({

type:"get",

url:"http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsSearch", //set ajax type to get //must have a specified API URL (iTunes API URL)

data:{term: searchterm, limit:"5"},

dataType:"jsonp",

success:function(data){

if(data.results.length > 0){

$.each(data.results,function(){

var newresult = $('<p style="line-height:30px;"></p>')

.html('<a href="'+this.previewUrl+'">'+this.trackName+'</a>');

newresult.prepend('<img src="'+this.artworkUrl30+'"/>');

newresult.appendTo('#results');

});

}else{

$('<p>No results found for: '+searchterm+'</p>').appendTo('#results');

$('#search').val('').focus();

}

}

});

});

}); //end function

</script>

Don't forget to include your jQuery CDN to the top of the document to allow the jQuery to function!