Before we begin here are some terms that you should become familiar with!
prepend
prepend inserts specified content at the beginning of the selected elements.
appendTo
appendTo allows you to insert HTML content at the end of selected elements.
ajax
ajax is a web development technique that is sued on the client side to create web applications.
What you will be learning.
Today you will be learning to add an Itunes Search to your site.
This will allow users to search through your site to find the top hits of something when searched through itunes. As well as the ability to preview said search results.
Code Required
HTML Markup
<div id="itunes">
<p>
<label for="search" id="title">Search: </label>
<input type="text" name="search" id="search" placeholder="Search for your favorite band"/>
<input type="button" id="submit" value="Search!"/>
</p>
</div>
<div id="results"> </div>
CSS Markup
#itunes{
margin: 0 auto;
width:400px;
}
#results{
margin: 0 auto;
width: 400px;
}
#results a{
text-decoration:none;
color:white;
padding-left:5px;
}
#results a:hover{
color:black;
}
Javascript Markup
$(document).ready(function(){
$('#submit').click(function(){
//add click function to button '#submit' to start function
var searchterm = $('#search').val();
//set variable of 'searchterm'
//val is the information entered into '#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" },
//setting the data and limit of results returned
dataType:"jsonp",
success: function(data){
if(data.results.length > 0){
$.each(data.results,function(){
var newp = $('<p style="line-height: 30px;"> </p>')
.html('<a href="'+this.previewUrl+'"'+this.trackName+''</a>');
newp.prepend('<img src="'+this.artworkUrl30+'"/>');
newp.appendTo('#results');
});
}else{
$('<p> No results found for: '+searchterm+'</p>').appendTo('#results');
$('#search').val('').focus();
}
}
})
});
});