By David Fekke
January 17th, 2011
I was speaking to one of my user group members, Luis Casillas, about Spry at our last meeting. I told him I had been thinking about writing a Spry example that searches YouTube tags, displays results, and even loaded the and played the Flash video.
Last night I sat down and took a look at the YouTube API. They use REST and XML-RPC interfaces to expose their api. They have good documentation on their dev site. I used the REST interface to call their tag search method in COldFusion. It returns an XML file that then consumes the XML through an ColdFusion proxy. This solves cross domain security issues, and allows the XMLHttpObj to call without security warnings. There is an example below.
<cfprocessingdirective pageencoding="utf-8" />
<cfsetting showdebugoutput="false" />
<cfparam name="url.tag" default="cat">
<cfset youTubeKey = "mykey" />
<cfset UTubeName = "myusername" />
<cfset methodName = "youtube.videos.list_by_tag" />
<cfset uTubeURL = "http://www.youtube.com/api2_rest?method=#methodName#&dev_id=#youTubeKey#&tag=#url.tag#" />
<cfhttp url="#uTubeURL#" charset="utf-8">
<cfcontent type="text/xml; charset=utf-8" />
All the rest was done in JavaScript, so the page only has to load once. All of the real functionality are Spry Ajax calls using the Spry.Data.XMLDataSet object.
I use one DataSet object to perform my searches with, and I wrote two functions to use a form perform the search, and another to display the YouTube Video. The JavaScript code is listed below;
var UTubeXPath = "/ut_response/video_list/video";
var dsYouTube = new Spry.Data.XMLDataSet(UTubeURL, UTubeXPath, { method: "GET", useCache: false });
function isdefined( variable)
{
return (typeof(window[variable]) == "undefined")? false: true;
}
function searchUTube() {
var myTag = document.myForm.tag.value;
UTubeURL = "youtubesearch.cfm?tag=" + myTag;
dsYouTube.setURL(UTubeURL);
dsYouTube.loadData();
if (isdefined("so")) {
YouTubeVideoDiv = document.getElementById("YouTubeVideo");
YouTubeVideoDiv.innerHTML = "";
}
}
function showVideo(myid) {
var swfFileName = 'http://www.youtube.com/v/' + myid;
so = new SWFObject(swfFileName, "mymovie", "425", "350", "7", "#336699");
so.write("YouTubeVideo");
}
<input type="text" name="tag" value="" />
<input onClick="searchUTube();" type="button" value="Search" />
<div id="mContainer" spry:region="dsYouTube">
<tr spry:repeat="dsYouTube"> <td valign="top">
Image
Title
<a href="{url}"><img src="{thumbnail_url}" />
<a href="#" id="{id}" onclick="showVideo(this.id);return false;">{title}
{description}
You can view a working example at this url.