Vimeo Instant Search using Jquery and PHP

I have found this article from Speckyboy.com. Instant Search is very popular among developers now a days. Web developers and Internet enthusiasts alike are very fond of online video services. One social video website Vimeo is a great example of how HD content can be stored and streamed across the planet. I love the quality you find with Vimeo uploads and the userbase is extremely knowledgeable on a wide variety of topics.

For this tutorial I want to explain how we can build a small Vimeo instant search webapp. I’ll be creating the frontend with jQuery and the backend on PHP. There is actually a full developer’s APIwith references for programmers. I’ll stick to explaining the more convoluted ideas so that you can follow along with my source code.

Vimeo Instant Search – Jquery

Contents

Initial Document Concept

I will first explain how we can put together the HTML document so it runs our frontend Ajax functions. Let’s include a reference to the most recent jQuery library which is used for Ajax calls. I’m also using another file v.js for our custom API commands.

Inside the body I have an input field used for search queries. The #results div will contain all the HTML output directly into our webpage. The whole index document is actually very small in comparison to the scripts. I’ve copied over the exact code below:

<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Vimeo Instant Search</title>
<meta name="author" content="Jake Rocheleau">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=McLaren">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="v.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>

<body>
<div id="w">
<div id="top" class="clearfix">
<h2>Vimeo Instant Search</h2>
<input type="text" name="s" id="s" class="sbox" tabindex="1" placeholder="Search videos...">
</div>

<div id="results" class="clearfix"></div>

</div><!-- /#w -->

</body>
</html>

Inside the results div we will include smaller divs with video content. This would make reference to the video title, thumbnail image, and the uploader’s name.

Backend API Dev in PHP

Let’s jump now into the backend coding in PHP. Afterwards we can tie in both frontend and backend interfaces to make our Ajaxified webapp. To start off I’m going to download a copy of the official Vimeo API wrapper in PHP.

We can simply include this file into our backend PHP document which I’ve named ajax.php. Any call we make on the backend will require an API public key and secret key. These are just long string hashes to authenticate your webapp. Head over to Vimeo’s developer page and sign up for a new application. The process is quick and shouldn’t take more than a couple minutes to complete.

Now we can start building the custom PHP file for Ajax response data. We’re going to be passing JSON content because this is the easiest output to loop through inside jQuery. Here are the first couple of lines inside ajax.php:

[php] header(‘Content-type: application/json’);

require_once(‘vimeo.php’);

$key = "PUBLICKEY";
$secret = "SECRETKEY";

$query = $_POST[‘q’];
$limit = 12; // number of videos to display for each search
[/php]

The header() function is necessary to determine what type of output we’re providing. Also the$query variable isn’t defined just yet, but we’ll be creating this inside JavaScript. It will contain the search string a user has entered into the form field.

[php] $vimeo = new phpVimeo($key, $secret);
$response = $vimeo->call(‘vimeo.videos.search’, array(‘per_page’ => $limit, ‘query’ => $query, ‘sort’ => ‘relevant’));

$jarray = array();
[/php]

Now we’re getting into the more complex PHP logic cycle. phpVimeo is referencing the class file we included from Github. This makes data access a whole lot easier and we can save hours of development time. The $jarray variable is simply an empty array for now. It will eventually contain data on 12 full videos from the search query, then gets passed into JSON.

Looping Through Return Data

With all the main PHP stuff setup we can move into the return content. Since we are working with multiple results this requires a foreach loop to quickly pass through all the related data. We will setup array keys inside the $jarray variable which will be repeated for each new entry.

[php] foreach($response->videos->video as $v){
$videoinfo = $vimeo->call(‘vimeo.videos.getInfo’, array(‘video_id’ => $v->id));

$jarray[] = array(
"thumbnail" => $videoinfo->video[0]->thumbnails->thumbnail[1]->_content,
"url" => $videoinfo->video[0]->urls->url[0]->_content,
"title" => $videoinfo->video[0]->title,
"username" => $videoinfo->video[0]->owner->display_name,
"userurl" => $videoinfo->video[0]->owner->profileurl,
"userpic" => $videoinfo->video[0]->owner->portraits->portrait[0]->_content
);
}

print_r(str_replace(‘\/’, ‘/’, json_encode($jarray)));
die();
[/php]

This code will work by pulling from our >$response data earlier. Each $response->videos->video object holds internal data which we need to pull out and save. This data specifically includes a video thumbnail, URL, and title, along with the uploader’s username, profile URL & photo.
The last print_r() function outputs all our data onto the page in JSON format. We need to remove escaped slashes from the output so it’s cleaner and easier to sort through. Then finally the PHP script calls die() to let Ajax know we are done using the asynchronous connection.

Custom jQuery Instant Search

So with the frontend and backend complete let’s tie everything together through JavaScript. I’m writing my code inside an external file v.js which begins like any typical jQuery document.

$(document).ready(function(){
var s = $("#s"); // search input field
var c = $("#results"); // results container
var t; // timer

$("#s").keydown(function(e){
clearTimeout(t);
if (!args) { var args = []; }

if (e.which === 65 && (e.ctrlKey || e.metaKey)) {
// allow the user to ctrl+a or cmd+a to select text
// without calling a new search function
} else {
t = setTimeout(function(){ vimeoSearch() }, 400);
}
});

The first few variables are shorthand for targeting the input search field, results div, and a numerical timer. Since people can often take extra time when typing, we need to give a delay before calling the API search. This is the purpose of a timer variable coupled with the JavaScript setTimeout()method.

Targeting the search field I have setup a new event listener for any .keydown() event. Each time the user enters a new key we will clear the previous timer to start fresh and run a simple if/else clause. If the user has entered CTRL+A or CMD+A then we do not run any search. This is associated with selecting all the text inside a search input and generally doesn’t constitute a new search query.

Otherwise the user has entered some new text and we’re pausing for 400 milliseconds, then calling a new function vimeoSearch().

Ajax Results Display

Inside my vimeoSearch() function we are performing a couple of tasks. First emptying out the contents div in case there are still previous search results displaying. Then we are creating a variable for the query string and appending a loader gif into the page while we await results.

function vimeoSearch() {
c.empty();
var q = s.val();

c.html('<img src="images/loader.gif" alt="loading..." id="loader">');

$.ajax({
type: 'POST',
url: 'ajax.php',
data: "q="+q,
success: function(data){

$.each(data, function(i, item) {
var code = '<div class="v"> <span class="details"><img src="'+data[i].userpic+'" class="userpic"> <h3>'+data[i].title+'</h3> <span class="user">uploaded by <a href="'+data[i].userurl+'" target="_blank">'+data[i].username+'</a></span></span> <a href="'+data[i].url+'" target="_blank" class="wrapping"><img src="'+data[i].thumbnail+'" alt="'+data[i].title+' video thumbnail" class="thumbnail"></a> </div>';

$("#loader").remove();
c.append(code);
}); // end each loop
},
error: function(xhr, type, exception) {
c.html("Vimeo Error: " + type);
}}); // end ajax call
} // end vimeoSearch() function

The whole function looks really long but there aren’t a lot of moving parts. The longest segment is inside the .ajax() method where we define some parameters and setup a success/failure callback function. If we access ajax.php and get a successful result then we need to loop through each of the JSON values.

This can be accomplished through jQuery’s .each() loop placed on the return data. After generating the full code we can remove the loader image and append all our new data. Otherwise we display a parse error on the page for any failed search queries. Most of the code is fairly straightforward and should be easy enough to follow.

View Demo Download Now

Please don’t forget to share and subscribe to latest updates of the blog. Also any comments and feedback are all welcome!
Thanks!

Original Source

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

Leave a Comment