Building a Simple AOL Video Search API Application Using Ajax

AOL Video Search

by Paul Sobocinski
January 16, 2007

Introduction

Today's website visitors have come to expect more from the Web--they want a more responsive experience. And they're getting it thanks to Ajax and other technologies that provide opportunities for rich user interaction over the Web. Websites are beginning to behave more and more like applications. The availability of tested APIs that provide server application components and services that can be accessed using Ajax and similar scripting technologies enables a single developer, or a small development team, to develop a rich application providing dynamic user interaction with robust back-end processing.

The AOL Video Search API allows us to build advanced web applications without having to spend time on server-side scripting. We also don't have to perform much client-side scripting related to the API, because the Ajax functions that interact directly with the server are already included in the API. This means that we can use the already-built AOL search engine framework without worrying about the internals of how it works. Furthermore, as the AOL API is based on Ajax technology, we can develop a web application that is highly dynamic and responsive to the user.

This article is meant to be an introduction to the AOL Video API, so only basic JavaScript and HTML knowledge is assumed. We don't go into the details of implementing Ajax (such as the XMLHttpRequest object) since the API takes care of this for us. Instead, we will use the AOL Video Search API to design and develop a simple Ajax video search application that can be easily incorporated into any website.

Preliminaries

Before you can use the AOL Video Search API, you must first set up an API account. Once you do this, you're assigned an application ID that you'll use every time you access the AOL server through the AOL Video API. When you register, be careful to specify the exact URL that your web application will be running from. The AOL server will only accept connections from this URL, and you cannot change this URL at a later time as it's tied to your application ID.

Throughout this article, we use a dummy application ID of 88. To get the code working on your website, substitute this dummy ID with the one you got when you set up your API account. Now that you have what you need to use the AOL Video Search API, we can start designing our web application.

General Design

Ajax web applications that use an independent API for server connectivity (such as the AOL Video API) can be treated as having three main components: the HTML page, the JavaScript application logic, and the API that is being used. See Figure 1 for details.

AJAX Web Application Components
Figure 1. Ajax web application components

The HTML page (yellow) is the component that actually interacts with the user, collecting input and displaying output. We can think of this component as the user interface layer of our application. Actions such as clicking a submit button in a form, or even moving your mouse, are known as DOM Events (arrow 1), where "DOM" refers to the Document Object Model. We can tie these events to certain JavaScript functions that we define (known as "Event Handlers"). By doing so, we can control the code that's executed when a user performs a certain action. For example, clicking on a submit button causes an onsubmit event to occur, which in turn can be tied to a function that handles this event by reading the form data and sending it to the server.

The JavaScript Application Logic (green) is where our custom JavaScript code is found, and is also the main focus of our discussion. As mentioned, it contains all of the DOM Event Handlers. In addition to interacting with the user through the HTML page, our JavaScript application must also interact with the AOL Server though the AOL Video Search API. This is achieved on two levels: through API Method3 Calls (arrow 2) and API Events (arrow 3). The API Method Calls allow us to access the API's functionality; namely the actual search engine on the AOL server. We can't expect an immediate response from the API due to connection and processing time. Therefore, the API provides us with its own set of API Events. Just as we do for the DOM Events, we define custom methods to handle these events in our JavaScript code. Once we have received the data that the user initially requested, we use the DOM to write this output to the HTML page, and fill in the HTML elements (arrow 4). Just as the JavaScript application logic depends on the HTML page to interact with the user, it depends on the AOL Video Search API to interact with the AOL server.

The AOL Video Search API (blue) is the final component of our application. Its role is to get the data that we need from the AOL server. The beauty of using an API in this case is that we don't need to worry about the inner logic of this component at all; we only need to know what it can do for us and what to expect from it. We'll cover these essentials later, and start with the top layer of our application: the HTML page.

A Simple Application

Let's start by taking a look at the HTML page, shown below. It's divided into three sections, labeled A, B, and C. Explanations follow the HTML code.

Code 1. HTML Page

<html>
 <head>
  <title> AOL Video Search </title>
  <!--A-->
  <script type="text/javascript" src="http://api.searchvideo.com/AOLVideoSearchAPIv3.js"></script>
  <script type="text/javascript" src="application.js"></script>
 </head>
<body>
 <!--B-->
 <form name="vidsearchform">
  <input type="text" name="searchterms">
  <input type="submit" name="searchsubmit" value="search videos" disabled>
 </form>
 <!--C-->
 <div id="status">html loaded, starting application...</div>
 <div id="results"></div>
</body>
</html>

A: Here is where we include the JavaScript code, which is composed of two parts. The first <script> tag links to the AOL Video Search API; without this inclusion we wouldn't be able to use the functions and methods discussed here. The second tag links to the JavaScript application logic that we will be developing from scratch.

B: This is a simple search form with only a text input and a submit button, the minimum required for search functionality. Strictly speaking, we don't need the submit button, as we can submit the form by pressing Enter in the text field. However, we've included a submit button for usability and clarity. This form is where our application receives user input. The search terms are entered in the text input box (named searchterms), and the content of this text input box is read by our application only when the form is submitted by clicking the submit button (named searchsubmit). For now, we have disabled the submit button by including the keyword "disabled" inside the <search> tag (we enable the form once the application is ready for searching).

C: Our application outputs data to the user by changing the contents of these <div> tags. The first one is for any status messages (including errors), while the second is for the actual search results. It is important to define the id attributes for these tags so that they can be easily accessed by the JavaScript application logic.

JavaScript Events and Handlers

The first event that occurs in our application is the DOM onload event. As this occurs once the HTML page is completely loaded, we should initialize our application within this event's handler. Let's have a look at the JavaScript code that accomplishes this:

Code 2. JavaScript for DOM onload Event

function onLoadH(e)
{
   /*C*/
   document.vidsearchform.onsubmit = onSubmitH;

   /*D*/
   displayStatus("Initializing search...");
   AOLVS = new AOLVideoSearch(appId);

   /*E*/
   AOLVS.attachEvent("onload", "onVInitializeH();");
   AOLVS.attachEvent("onupdate", "onVUpdateH();");
   AOLVS.attachEvent("onerror", "onVErrorH(errorCode, errorMessage);");

   /*F*/
   AOLVS.initialize();
   return true;
}

/*A*/
var AOLVS = null;
var appId = "88";

/*B*/
window.onload = onLoadH;

A: The global variables. These are visible to all functions in our application. The first will contain the object that exposes all of the API methods and attributes. In other words, we will access the features of the AOL Video API by calling this object's methods and reading its attributes. The second variable contains your application ID, which is assigned to you when you get your API account (discussed earlier).

B: The DOM onload event is defined here. We must define the remaining events inside the onload event handler, because the entire HTML page must be loaded to attach events to specific HTML elements. We've chosen to name the function onLoadH(), but this is completely arbitrary. The function is defined at the top of the Code 2 snippet.

C: The first thing we do in the function onLoadH() is to define the remaining DOM event handler functions. Due to the simplicity of our application, we are only concerned with the onsubmit event. Support for more event handlers can be added here when the application is extended for more functionality. The onsubmit event is assigned to the function onSubmitH(), which we will discuss later. The onsubmit event occurs when the HTML form (labeled "B" in "code 1") is submitted. This can happen either when the form's submit button is clicked, or Enter is pressed when the cursor is focused on the text input field of the form. We use the notation document.vidsearchform.onsubmit to assign the onsubmit event handler specifically to our vidsearchform form. This way, if there are any other forms in the HTML, they will not interfere with our application.

D: Here we use the function displayStatus() to indicate to the user that the video search application is being loaded. This is a custom JavaScript function that is part of our application; its inner workings will be covered later. Following this, we see the main constructor, which creates the API object. As mentioned in the Code 2 "A" discussion, we have declared this object globally so that all JavaScript functions on the page have full access to it. We pass a single attribute to the constructor: appId. This contains the application ID you received when you registered for your API account.

E: Here we assign the API events. While the syntax for assigning API events differs from the syntax for assigning DOM events, it's still straightforward: we use the function attachEvent(). This function takes two attributes: the name of the event, and the name of the function that is called when the event occurs. The AOL Video API supports three events: onload, onupdate, and onerror. The API events are described in more detail later in this article.

F: Lastly, we call initialize() to fully prepare the API object for use. This function connects to the AOL server, ensures that the search engine is ready to use, and verifies the supplied application ID. Once this is all complete, the API onload event is fired. As shown in Code 2 "E," we have assigned the function onVInitializeH() to handle this event. We define this function next.

Code 3. JavaScript for Video Search API onload Event

/*A*/
function onVInitializeH()
{
   setSearchDisabled(false);
   displayStatus("Search ready.");
   return true;
}

/*B*/
function displayStatus(statusstring)
{
   document.getElementById("status").innerHTML = statusstring;
}

/*C*/
function setSearchDisabled(isdisabled)
{
   document.vidsearchform.searchsubmit.disabled = isdisabled;
   document.vidsearchform.searchsubmit.value = (isdisabled) ? "search submitted" : "search videos";
}

A: As the API's search functionality is now available, we indicate this to the user and enable the form for searching. The function setSearchDisabled() is used to both enable and disable the form; passing false will enable it. We used displayStatus() previously in onLoadH() (see Code 2 "D").

B: The implementation of displayStatus() is quite simple, consisting of one line of code. Nevertheless, it's worth defining a separate function for this, anticipating future extensions to the functionality. For example, we may want to add dynamic GUI effects such as fading and sliding that would require more than one line of code. For now, employ the minimalist approach and just write our status message to the innerHTML of the <div> status element. As we have used the id attribute to label the element, we can easily reference it by using the getElementById() function. This function is both widely supported by browsers and convenient to use, so we will use it often in our application.

C: As the DOM allows us to easily reference form elements, the implementation of setSearchDisabled() also avoids complexity. The first line directly accesses the form's submit button by its name (searchsubmit). The attribute disabled determines whether or not the button is disabled, so we simply set it equal to the Boolean attribute that's been passed to this function. The second line is a condensed if-then-else statement; it determines what we should set the button's value attribute to (i.e. the button's label that's visible to the user). The only time that we'll be disabling the form is when a search is being performed, so the label "search submitted" is shown when the button is disabled. On the other hand, "search videos" is shown when the search is ready (i.e. the submit button is enabled).

Overview of onload

We have just covered all of the code necessary to fully load up the HTML page and initialize the AOL Video API for use. This sequence of events is triggered when the HTML page loads; in other words, when the DOM onload event occurs. Using the color conventions of Figure 1, we can graphically summarize all of what we have discussed so far, in Figure 2 below:

The Application onload Processing Sequence
Figure 2. The Application onload Processing Sequence

Adding Search Functionality

Now we can move on to developing the main purpose of our application: searching for videos. Submitting the HTML form results in the DOM onsubmit event being triggered for the form named vidsearchform. This in turn invokes the onSubmitH() function, shown below:

Code 4. Search Form Search Terms Submit JavaScript

function onSubmitH(e)
{
   /*A*/
   var searchterms = null;

   if (document.vidsearchform.searchsubmit.disabled)
      return false;

   /*B*/
   setSearchDisabled(true);
   searchterms = getSearchTerms();
   AOLVS.getVideos(searchterms);
   displayStatus("Query submitted. Waiting for results...");

   /*C*/
   return false;
}

/*D*/
function getSearchTerms()
{
   return document.vidsearchform.searchterms.value;
}

A: First, we declare the local variable searchterms, which we use to store the user input that's to be used to search for videos. The if statement that follows checks if the form's submit button is disabled--if it is, we exit the function. This extra precaution is necessary because an HTML form can also be submitted by pressing Enter when the form is in use (e.g. after you type a string in the text input box). As disabling the submit button doesn't stop the form from being submitted in this case, we include this if statement.

B: At this point, we know that the user input is ready to be used for searching. The first thing we do is to disable the search form, because we need to process one search request before we process another. Next, we get the user input from the form by invoking the getSearchTerms() function (explained in "D" below), passing the returned value to the AOL Video Search object using the getVideos() API function. We will explain how these results become available to us, and how we process them, when the next code segment is introduced.

C: All event handler functions must return a Boolean value, and it's considered good programming practice to explicitly specify this value. If we were to omit this return statement, the onsubmit handler would return true. It's crucial that we don't let this happen, as this would cause the entire HTML page to be refreshed, resetting the state of the application. Whenever a form is implemented in Ajax, the onsubmit handler will always return false to prevent this from occurring.

D: The function getSearchTerms() gets the search terms entered by the user in the HTML form by directly accessing the form's input element by its name, searchterms. The value attribute is what actually contains the string input by the user. By dedicating a separate function for this, we can add functionality such as input filtering and validation here. For example, we can block any non-alphanumeric characters from being entered, as these will be ignored by the video search.

After the getVideos() function is called, the AOL Video Search API sends the search terms input by the user to the AOL server. After some time has passed, the results are returned. In order to indicate to our application that the results are ready to be processed, the API triggers an onupdate event--we associated our onVUpdateH() handler function to this event earlier (see Code 2 "E"). We now explain the details of this function, as well as the displayResults() function, which processes the results and displays them to the user.

Code 5. Video Search Results Handler and Display

/*A*/

function onVUpdateH()
{
   displayResults();
   setSearchDisabled(false);
   displayStatus("Results returned.");
   return true;
}

function displayResults()
{
   /*B*/
   var outputhtml = "";

   for (var i=0; i < AOLVS.VideoSet.totalResultsReturned; i++)
   {
      outputhtml += "<div>";

      /*C*/
      outputhtml += "<a href='" + AOLVS.VideoSet.Video[i].videoUrl + "'>";
      outputhtml += AOLVS.VideoSet.Video[i].title + "</a>";
      outputhtml += "<p>" + AOLVS.VideoSet.Video[i].description + "</p>";
      outputhtml += "</div>";
   }

   outputhtml += (AOLVS.VideoSet.totalResultsReturned == 0) 
      ? "<div>No videos found.</div>" : 
      "<div>(end of results)</div>";

   /*D*/
   document.getElementById("results").innerHTML = outputhtml;
}

A: The API onupdate event handler that we define here is fairly straightforward. The only function that we haven't seen before is displayResults(). We'll explain the inner workings of this function shortly. As the search is now complete, we can enable the search form by calling setSearchDisabled(false). Finally, we let the user know of the status of the application by calling displayStatus().

B: The function displayResults is one of the most important that we implement, as it is responsible for actually displaying the search results to the user. The local variable outputhtml contains the search results, properly formatted with HTML tags. The for loop traverses the collection of Video objects that is returned by the AOL Video Search API. The attribute VideoSet.totalResultsReturned tells us how many videos we have to go through.

C: VideoSet.Video is an array of Video objects that contain all video information returned by the video search. Although there are many attributes that we could use, we focus on three for now: videoUrl, title, and description. Here is the complete documentation on the data contained in the VideoSet object and the VideoSet.Video array of objects.

D: Once outputhtml is ready, we write it to the <div> element that we've designated in the HTML to contain the results. This element is identified by the ID results. We use the getElementById() function to do this, which we've explained earlier.

Overview of onSubmit

Now that our application is able to get input from the user, send it to the AOL server, and display the retrieved results in the browser, we have achieved what we set out to do. The search functionality just covered is summarized in Figure 3:

Video Search and Results Display Processing Sequence
Figure 3. Video Search and Results Display Processing Sequence

Error Handling

Although strictly not necessary for basic functionality, we include error handling in the application so that we'll receive as much information as possible if something goes wrong. We define an API onerror event handler that simply displays the error to the user. When an error occurs, the user is notified by getting a message in the status <div> element. In addition to informing the user on what's going on, it's useful as a debugging tool. Here's our simple API onerror event handler function:

function onVErrorH(code,message)
{
   setSearchDisabled(false);
   displayStatus("Error: " + message + " (code " + code + ")");
   return true;
}

Unlike the other event handler functions, this one takes two attributes: code and message. The values of these attributes directly come from the API, and provide information about the specific error that occurred. The value of code is a number, while message is a descriptive text string. As a general rule, the error code is meant to be used by the application, while the error message is for the end user. We keep it simple here; our application doesn't make use of the value stored in code. We just display both the code and the message to the user. Calling setSearchDisabled(false) enables the search form so that the user can try again, in a situation where the search caused the error.

Conclusion

Congratulations! We have successfully developed an Ajax web application that allows a user to search for videos on the AOL server. In using the AOL Video Search API, we were able to focus on the JavaScript application logic responsible for interacting with the user and displaying the search results. By defining custom functions whenever possible, we have designed an application that is highly extendable--the code could be used in an HTML page with an advanced design template, and the user interfacing functions can be elaborated upon to allow for more visual complexity.

We have only scraped the surface of the AOL Video Search API's capabilities. In future articles, we will discuss further potential of the API, such as managing large result sets, exposing more search result attributes as extra features to the end user, and discussing precautions and approaches on security. The complete source code of the application that we've covered is contained in two files, available below.

Resources

References

Without words!

Excellent work!
Bst Rgds,
Michael B.