In this tutorial I will be showing you how to build a simple tool that will use Yahoo!’s YQL query tool to search for some tracks from their music website. These results will then be displayed on our website all using AJAX to make it seamless along with a link to buy the album off Amazon.
Live Demo
Download

YQL stands for Yahoo! Query Language, it lets you query, filter, and join data across most of Yahoo!’s (and a few other’s) services with a similar structure to SQL. This is useful as its all written in one language making it easier to build sites and web apps that will use different services but join them all together. To get started with seeing what YQL looks like its a good idea to try out their YQL Console. From this we can see that it will deliver our content back in either XML or JSON, in this tutorial we will be using JSON. The format of YQL was built to be very similar to that of SQL so it makes learning it even easier.
Getting started
To get started we need a blank HTML document, CSS file, JS file and a few images for the design. I used HTML Boilerplate to provide the base structure of my files. In the index.html file we want to add the following HTML:
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Search Using YQL and AJAX | Brenelz.com</title>
<meta name="author" content="Alex Bor">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="css/style.css?v=2">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="container">
<div id="search_cover">
<div id="search_box">
<input type="text" placeholder="Search using YQL and AJAX" id="music_search" />
<img src="images/loader.gif" id="loader" alt="Loading..." width="16" height="11" />
</div>
</div>
<div id="search_results">
<!-- Our search results will be places in this area -->
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>
<script src="js/script.js"></script>
<?php include_once($_SERVER['DOCUMENT_ROOT']."/includes/meta.php"); ?>
</body>
</html>
In the HTML we are simply getting jQuery from Google’s library in the footer after we have created a basic structure for our site. The following CSS will then style our page.
/* HTML5 ✰ Boilerplate */
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
blockquote, q { quotes: none; }
blockquote:before, blockquote:after,
q:before, q:after { content: ''; content: none; }
ins { background-color: #ff9; color: #000; text-decoration: none; }
mark { background-color: #ff9; color: #000; font-style: italic; font-weight: bold; }
del { text-decoration: line-through; }
abbr[title], dfn[title] { border-bottom: 1px dotted; cursor: help; }
table { border-collapse: collapse; border-spacing: 0; }
hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }
input, select { vertical-align: middle; }
body { font:13px/1.231 sans-serif; *font-size:small; }
select, input, textarea, button { font:99% sans-serif; }
pre, code, kbd, samp { font-family: monospace, sans-serif; }
html { overflow-y: scroll; }
a:hover, a:active { outline: none; }
ul, ol { margin-left: 2em; }
ol { list-style-type: decimal; }
nav ul, nav li { margin: 0; list-style:none; list-style-image: none; }
small { font-size: 85%; }
strong, th { font-weight: bold; }
td { vertical-align: top; }
sub, sup { font-size: 75%; line-height: 0; position: relative; }
sup { top: -0.5em; }
sub { bottom: -0.25em; }
pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; padding: 15px; }
textarea { overflow: auto; }
.ie6 legend, .ie7 legend { margin-left: -7px; }
input[type="radio"] { vertical-align: text-bottom; }
input[type="checkbox"] { vertical-align: bottom; }
.ie7 input[type="checkbox"] { vertical-align: baseline; }
.ie6 input { vertical-align: text-bottom; }
label, input[type="button"], input[type="submit"], input[type="image"], button { cursor: pointer; }
button, input, select, textarea { margin: 0; }
input:valid, textarea:valid { }
input:invalid, textarea:invalid { border-radius: 1px; -moz-box-shadow: 0px 0px 5px red; -webkit-box-shadow: 0px 0px 5px red; box-shadow: 0px 0px 5px red; }
.no-boxshadow input:invalid, .no-boxshadow textarea:invalid { background-color: #f0dddd; }
::-moz-selection{ background: #FF5E99; color:#fff; text-shadow: none; }
::selection { background:#FF5E99; color:#fff; text-shadow: none; }
a:link { -webkit-tap-highlight-color: #FF5E99; }
button { width: auto; overflow: visible; }
.ie7 img { -ms-interpolation-mode: bicubic; }
body, select, input, textarea { color: #444; }
h1, h2, h3, h4, h5, h6 { font-weight: bold; }
a, a:active, a:visited { color: #607890; }
a:hover { color: #036; }
/*
// ========================================== \\
|| ||
|| Your styles ! ||
|| ||
\\ ========================================== //
*/
.clear { clear: both; }
#container { width: 600px; height: 100%; margin: 0 auto; background: url(../images/music_note.jpg) top center no-repeat; min-height: 470px; padding-top: 50px; }
#search_cover { background: #e4eeff; border: 1px solid #90b9ff; padding: 5px; position: relative; }
#music_search { background: none repeat scroll 0 0 #FFFFFF; border: 1px solid #BFBFBF; color: #595959; font-family: Arial, "Helvetica Neue", Helvetica, sans-serif; font-size: 17px; font-weight: bold; height: 25px; padding: 10px 60px 10px 10px; width: 515px; }
#loader { height: 20px; position: absolute; right: 18px; top: 17px; width: 30px; display: none;}
.music_item { background: none repeat scroll 0 0 #90B9FF;
border: 1px solid blue;
float: left;
margin: 7px;
padding: 3px;
text-align: center;
width: 175px; }
.music_item span img { display: block; display: block; margin-left: auto; margin-right: auto; }
This CSS will style our page and also provide a reset for default behaviours that some browsers set. After this we should now have a base to start working with.

In the HTML and CSS we can see that we will fill our results into the “#search_results” div. I have also linked to a gif loading image that we will show when we are searching for content and hide once its finished.
I will be using the JavaScript framework jQuery which we loaded in towards the bottom of our index.html file. Here is the JavaScript which has a few comments in the code.
$(function(){
//Default variables and objects so we don't need to
//select them each time
var search_box = $('#music_search'), //Where we will write the text
loader = $('#loader'), //Loading gif
search_results = $('#search_results'), //Where the results will be places
runner = ''; //A variable to check if a request is running
var music = {
search: function(string){
runner = $.ajax({
url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20music.track.search%20where%20keyword%3D%22'+string+'%22&format=json&diagnostics=true&callback=',
dataType: 'json',
success: function(json){ parse_results(json.query) }
});
},
show_loader: function(){
loader.fadeIn();
},
hide_loader: function(){
loader.fadeOut();
}
}
function parse_results(json){
search_results.html('');
if(json.results === null){
search_results.html('No results found.');
music.hide_loader();
return;
}
//Loop through tracks
var ii = 0;
$.each(json.results.Track, function(i, item){
if( typeof item.Album != 'undefined' && item.Album != null ) {
if( typeof item.Album.Release != 'undefined'){
if( typeof item.Album.Release.Image == 'undefined'){
$image_url = 'images/no_image.jpg';
}else{
$image_url = item.Album.Release.Image[5].url;
}
search_results.append('<p class="music_item"><span><img src="'+$image_url+'" /><span class="album_title">'+item.Album.Release.title+'</span></span> - <a href="http://www.amazon.com/s/ref=nb_ss_d?url=search-alias%3Ddigital-music&field-keywords='+item.Album.Release.title+', '+item.Artist.name+'">Buy</a></p>');
}
ii++;
if(ii == 3)
{
search_results.append('<p class="clear"></p>');
ii = 0;
}
}
});
}
search_box.keyup(function(){
music.show_loader();
if(runner != ''){
runner.abort();
//console.log('Aborted');
}
setTimeout( function() {
music.search(search_box.val());
}, 1000 );
music.hide_loader();
});
});
At the top of this file we create some of our default variables which we are going to use throughout the script.
After this we create our variable object “music”. I chose to create this part similarly to a plugin for ease of use later on. Next we will create 3 functions in this object, on to search Yahoo! using the YQL, and two to show and hide the loader. Our music.search function requires a string which will be the value of the search box, which will be used to search the YQL database. In the music.search we need to set up our AJAX request which requires 3 parameters: URL, datatype and the success callback.
We can use the YQL Console to produce our request URL. From the drop down on the right hand side if we select “music” we can see a list and few examples of what we can search/do with Yahoo!’s music tool and YQL. We are using “music.track.search” to provide our search results.

From above all we need to do is copy the URL and replace “Madonna” with our string we want to search.
The parse_results function will then handle all the work of making sure there is a track and displaying it in the results area along with a handy link to buy it from Amazon.com. While printing out each of our tracks if an image isn’t found we show default “no image” instead.
Our final bit of code ties it all together adding an event listener on the search box. The listener checks for a “key up” on the search box so when someone starts to type a search is fired (and if search is currently running it is aborted).
That’s about all we need to get started with using YQL. As we can see its a very useful tool and this is just a short guide to what can be done with it. I hope that this gave a good overview of an example and explain a bit about YQL.
For more information be sure to read the Yahoo! guide as this is a really powerful tool with many possibilities with what can be done with it!
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!