We all love Facebook. You can catch up with friends, family or colleagues, meet new people, share photos, links and whatnot. One of the most striking feature of Facebook's timeline is inline content embedment. It enables you to view content from third-party websites without having to visit the site. Facebook might be using oEmbed with a lot of modification of their own. Over the last weekend, I tried to create a mock-up of Facebook's inline content embedment with jQuery oEmbed and some AJAX. This tutorial is about how you can create it on your own. I hope you'd enjoy it. :-)
Download Source Try Demo
You might also like:

What is jQuery oEmbed?

oEmbed is an open format which allows sites to embed content from third party sites. You can embed photos, videos, documents, flash players or any other rich multimedia contents (from selected sites). oEmbed is supported by an array of popular sites — from Flickr to Youtube to Vimeo, among others. jQuery oEmbed is a plugin that uses the oEmbed API to embed content. It's super lightweight (minified version is 4KiB) and, like most jQuery plugins, simple in its use. Here's the syntax:
<script type='text/javascript'>
// attach jQuery and jQuery.oembed plugin before this point
$(function(){
 $("a.embed").oembed();
});
</script>
<!-- HTML -->
<a href='http://www.youtube.com/watch?v=8JRICTFnViM'>PHP Tutorial on YouTube</a>
jQuery.oEmbed creates div with class-name "oembed-container" and embeds the content in it.

Application Flow

Our application would be simple — it will post the messages users post and converts links to embedded content. Below is the flow chart of how it's going to work.

Create the layout

Our layout is simple, as the application itself.
Put these lines of code in index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Facebook Like Status Update with jQuery oEmbed</title>
</head>
<body>
<div id='wrapper'>
 <div id='updateBox'>
  Enter Your Message here...
   <textarea id='statusMsg'></textarea>
   <button id='shareBtn'>Share</button>
   (No HTML, only links and text)
   <div class='clear'></div>
 </div>
 <div id='msgs'>

 </div>
</div>
</body>
</html>
Here, we create a wrapper and put all the elements in it. Each message will be put in a div with class name "msg".

CSS

For the CSS, I chose the colors and the layout in a way so that it resembles Facebook. You can choose any color you wish.
html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote,
pre, form, fieldset, table, th, td { margin: 0; padding: 0; }

body {
font-family:"lucida grande",tahoma,verdana,arial,sans-serif;
font-size: 14px;
line-height:1.3em;
text-align:center;
}

a, a:visited {
outline:none;
}

.clear {
clear:both;
}

img {
 border:0;
}

#wrapper {
width:480px;
margin:0 auto;
text-align:left;
}

#updateBox {
 background-color:#F2F2F2;
 border:1px solid #B5B5B5;
 padding:4px;
}

#statusMsg {
 width:100%;
 height:70px;
 border-color:#7C7C7C #C3C3C3 #DDDDDD;
 border-style:solid;
 border-width:1px;
}

#shareBtn {
 background:#5872A7;
 float:right;
 color:#ffffff;
 font-weight:bold;
 border:0;
 padding:4px;
 margin-top:2px;
}

#msgs {
}

.msg {
 margin-top:8px;
 border-bottom:1px solid #B5B5B5;
 padding-bottom:4px;
 color:#808080;
 font-size:13px;
}

.msg a {
 color:#3B5998;
 text-decoration:none;
}

.msg a:hover {
 text-decoration:underline;
}

.oembed-container {
 border-left:2px solid #eaeaea;
 margin-left:15px;
 padding:4px 4px 4px 10px;
}
There's nothing much about the CSS that needs explanation. Only the "oembed-container" class. jQuery.oEmbed, by default, creates a div with class-name "oembed-container". We put some styles to distinguish the embedded content.

The Database and Table

We need a table to store the status messages. I created a very simple table with only two fields — id and content. id is the numeric id of the status message and content is the status message text. To create a table like this, use the following SQL code.
CREATE TABLE `status_msgs` (
  `id` int(11) NOT NULL auto_increment,
  `content` text,
  PRIMARY KEY  (`id`)
);
Please note that the table super-simple. Most applications have a user_id field in such tables to identify which user posted the status. But for this simple tutorial, I avoided all this. If you have queries, use the comment form below. :-)

Connect to the Database

Create a new file and save it as config.php. Put the following code in it.
<?php
 $host = "HOST"; //your hostname. it's "localhost" in most cases
 $username = "USERNAME"; //your username
 $password = "PASSWORD"; // your password
 $db = "DB"; // name of the databae
 
 mysql_connect($host, $username, $password) or die("Cannot connect to database.");
 mysql_select_db($db) or die("Cannot select the database.");
?>
Do change the credentials with yours.

Create the Timeline

When the page is loaded we want the user to see what's posted on the timeline. So, we connect to the database and fetch all the statuses and create a div for each status. The following lines of code will do it. Add them inside <div class='msgs'></div>
<?php 
   include("config.php");
   $q = "SELECT * FROM status_msgs ORDER BY id DESC";
   $r = mysql_query($q);
   if(mysql_num_rows($r) > 0) {
    //updates are found
    while($row = mysql_fetch_assoc($r)){
     echo "<div class='msg'>\n";
     echo $row['content']."\n";
     echo "</div>\n";
    }
   } else {
    //nothing in the table.
    echo "No update found in the database!";
   }
?>
Also, we add this few lines of code inside <head> tag of index.php to enable oEmbed on the links in the timeline.
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js'></script>
<script type='text/javascript' src='jquery.oembed.min.js'></script>
<script type='text/javascript'>
$(function(){
 $(".msg a").oembed(null, {
 embedMethod: "append",
 maxWidth: 480
 });
});
</script>
Don't forget to place jquery.oembed.min.js in the same directory as index.php

Post Status Messages via AJAX

Now, it's time we add some AJAX functionality to our little application. When the user clicks on share button, we do two things with the help of before submitting it via AJAX. The first thing is to check and remove all HTML tags from the status messages. Secondly, we have to replace URLs with HTML anchor tags. Create new file, functions.js, and put the following two functions in it.
function stripHTML(source){
 var strippedText = source.replace(/<\/?[^>]+(>|$)/g, "");
 return strippedText;
}

function replaceURLWithHTMLLinks(source) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
   replaced = source.replace(exp,"<a href='$1' target='_blank'>$1</a>"); 
   return replaced;
}
The first function removes all HTML tags and the second function (source: StackOverflow) replaces URLs with HTML anchor tags. (If you're wondering what the functions are, I used Regular Expressions.) Attach functions.js to index.php by adding this line inside <head> tag.
<script type='text/javascript' src='functions.js'></script>
Next, we add these few lines of code inside the <head> tag of index.php
<script type='text/javascript'>
$(function(){
 $("#shareBtn").click(function(){
  status_text = $("#statusMsg").val();
  if(status_text.length == 0) { //nothing entered
   return;
  } else {
   $("#statusMsg").attr("disabled", "disabled"); //disable the textarea while ajax is in process
   status_text = stripHTML(status_text); // clean all html tags
   status_text = replaceURLWithHTMLLinks(status_text); // replace links with HTML anchor tags.
   $.ajax({ //make ajax request
    url: "ajaxUpdate.php",
    type: "POST",
    data: "status_msg="+status_text,
    success: function(msg) {
     $("#statusMsg").val(""); //clear the textarea
     $("#statusMsg").attr("disabled", "");
     if(msg == "true") { //msg is posted
      $("#msgs").prepend("<div class='msg'>"+status_text+"</div>"); //add the posted msg to timeline
      $(".msg:first a").oembed(null, {maxWidth: 480, embedMethod: "append"}); //oEmbed links of the posted msg 
     } else { //failed
      alert("Cannot be posted at the moment! Please try again later.");
     }
    }
   });
   return false;
  }
 });
});
</script>
Above code works when the user clicks on the Share button. When no text is entered, nothing happens. If text is entered, we use those JavaScript functions to remove HTML and turn URLs to HTML anchor tags. After sanitizing the text, we make AJAX request to ajaxUpdate.php (which we will create). If the response is "true", the posted message is added to the timeline, and the links in the message are converted to embedded content. If the response is not "true", we alert the user that the message cannot be posted at the moment. We put the following code in ajaxUpdate.php
<?php 
include("config.php");
if(!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
 {
 die("No direct access to files is allowed");
 }
if(!empty($_POST['status_msg'])){
 $q = "INSERT INTO status_msgs (content) VALUES ('{$_POST['status_msg']}')";
 $r = mysql_query($q);
 if(mysql_affected_rows() == 1) {
  echo "true";
 } else {
  echo "false";
 }
}
?>
This is fairly simple — first, we make sure that the page is accessed only via AJAX. Then we check to see that the status message text is non-empty. If it is not empty, we insert the message to the table and "true" is printed. "false" otherwise. That is it!

Conclusion

oEmbed also has a PHP library. If you're looking for more control over your application, you may find it helpful. I hope you enjoyed the tutorial. If you have queries, feel free to use the comment form below.

Labels: , ,

blog comments powered by Disqus