9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Wednesday, August 25, 2010

Facebook Style Tag Friends with Jquery, Ajax and PHP

I received a request from my reader that asked to me how to implement Facebook like tag friends in your status or update box. It is great feature to adding friends start with @ symbol. I had tried this with Jquery, Ajax and PHP, it's simple just collabration of my previous posts.

facebook tag friends with jquery

Download Script     Live Demo

Sample Database
create database table with name "user_data"
CREATE TABLE user_data
(
uid INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(25),
lname VARCHAR(25),
country VARCHAR(25),
img VARCHAR(50)
);

Previous Post: Facebook like Autosuggestion with jQuery, Ajax and PHP.

tagfriends.html
Contains javascipt and HTML code. $("#contentbox").live("keyup",function(){}- contentbox is the id name of update box(div tag). Using $(this).text() calling updatebox value.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var start=/@/ig; // @ Match
var word=/@(\w+)/ig; //@abc Match

$("#contentbox").live("keyup",function()
{
var content=$(this).text(); //Content Box Data
var go= content.match(start); //Content Matching @
var name= content.match(word); //Content Matching @abc
var dataString = 'searchword='+ name;
//If @ available
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
//if @abc avalable
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php", // Database name search
data: dataString,
cache: false,
success: function(data)
{
$("#msgbox").hide();
$("#display").html(data).show();
}
});
}
}
return false();
});

//Adding result name to content box.
$(".addname").live("click",function()
{
var username=$(this).attr('title');
var old=$("#contentbox").html();
var content=old.replace(word," "); //replacing @abc to (" ") space
$("#contentbox").html(content);
var E="<a class='red' contenteditable='false' href='#' >"+username+"</a>";
$("#contentbox").append(E);
$("#display").hide();
$("#msgbox").hide();
});
});
</script>
//HTML Code
<div id="container">
<div id="contentbox" contenteditable="true">
</div>
<div id='display'>
</div>
<div id="msgbox">
</div>
</div>
$(".addname").live("click",function(){}- addname is the class name of anchor tag(autosuggestion list). Using $(this).attr('title') calling anchor tag title value.

Note : contentbox div tag contenteditable="true"

boxsearch.php
<?php
include('config.php');
if($_POST)
{
$q=$_POST['searchword'];
$q=str_replace("@","",$q);
$q=str_replace(" ","%",$q);
$sql_res=mysql_query("select * from user_data where fname like '%$q%' or lname like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['fname'];
$lname=$row['lname'];
$img=$row['img'];
$country=$row['country'];
?>
<div class="display_box" >
<img src="user_img/<?php echo $img; ?>" class="image" />
<a href="#" class='addname' title='<?php echo $fname; ?>&nbsp;<?php echo $lname; ?>'>
<?php echo $fname; ?>&nbsp;<?php echo $lname; ?> </a>
</div>
<?php
}
}
?>

CSS
#container
{
margin:50px; padding:10px; width:460px
}
#contentbox
{
width:458px; height:50px;
border:solid 2px #333;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;
text-align:left;
}
#msgbox
{
border:solid 1px #dedede;padding:5px;
display:none;background-color:#f2f2f2
}
#display
{
display:none;
border-left:solid 1px #dedede;
border-right:solid 1px #dedede;
border-bottom:solid 1px #dedede;
overflow:hidden;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede; font-size:12px; height:30px;
}
.display_box:hover
{
background:#3b5998;
color:#FFFFFF;
}
.image
{
width:25px; float:left; margin-right:6px
}

Facebook Cookbook: Building Applications to Grow Your Facebook Empire
Comments
{ 58 comments }
Anonymous said...

pz tell me in xml not with config.php

Anonymous said...

Wonderful post bro. I am a big follower of 9lessons. All your posts are very good.

Lucifix said...

Was that my request? :)

Anyway tutorial is not working in Firefox, otherwise tried in IE and everything looks great ;)

Anonymous said...

Great work. Very nice & useful script... :)

Arun diundi said...

wow great bro.really cool

buzzknow said...

Hi, actually you can achieve some selector to and create custom friend selector like this example ..


http://labs.buzzknow.com/facebook/_app/customfriendselector/

this is use for iframe application and require latest facebook sdk :)

cheers 9lessons

Srinivas Tamada said...

@Lucifix

Working fine in Firefox

mitendra said...

very nice.Love this script

aran said...

You really need to add security to these tutorials. These scripts your showing people are open to SQL Injections!

Anonymous said...

it's not working in my firefox too (3.6.8, windows)

Anonymous said...

This is Like magic..Nice one broh

Anonymous said...

its not work...why..

Josh J said...

What if my friend's name was:

@'; DROP TABLE user_data;--

Your query would be:

select * from user_data where fname like '%'; DROP TABLE user_data;--%' or lname like '%'; DROP TABLE user_data;--%' order by uid LIMIT 5

Bye bye user_data table

DO NOT USE THIS SCRIPT AS-IS!! IS IS VULNERABLE TO SQL INJECTION ATTACKS

dskanth said...

Hey... Josh J is right...
We also have to take care about those SQL injection attacks... :(

Cant use the script as is.. please make few corrections.

Srinivas Tamada said...

I'm just giving an idea. Why u people talking about SQL injections

Anonymous said...

he is already showed the concept, cant you people just add the safety measurement yourself?

if you cannot do basic stuff such as protect sql injection, then you are not qualified to use this code.

Anonymous said...

Yes, Srinivas is absolutely right. Thanks Srinivas.

Anonymous said...

This is nice work.no matter what people are saying.But Joshua is very intelligent man.To discover such a bug.But awesome tutorial thank..Am IN TANZANIA

Anonymous said...

NOT WORKING IN FIREFOX 3.6

Cricket La Chica said...

Not working in FF 3.6.10 (Mac). I'm getting this JS error: http://imgur.com/SmMrD.png. Hope this helps!

Pradyut said...

return false()!!! function thori na hai...
right code... return false;

Purdey said...

hi does it also work if i have an textarea???!
What is to change ? thank you

Anonymous said...

Josh J said it is vulnerable to SQL Injection attacks, but which code can't be fixed? It can easily be fixed using bind params. lol..

gunfire said...

great script...
but i wonder,,it is only provide 1 tag person only?because i try in firefox 3.5 its run good in multiple tag, but in chrome, and opera only provide 1 tags only...
thx b4 for the help...

Anonymous said...

In the real world, you're going to deal with adversaries who will try to break your code. So yes, security is an important issue that you cannot ignore.

Diane said...

But this is a div, how about a textarea?

Guna B.Sc(Che)., MCA said...

This not working for multiple tagging, It works only for first memeber....

ramya said...

The dropdown is to be focused when we type something in the textarea. the dropdown should be navigated with arrow keys like in facebook. it is not working like facebook status tagging. can you please any one help me to develop like in facebook

picas.line said...

hi Sri,
this was Great Code..

but it would be perfect with submit function..
or can you provide us example using input text or textarea..

Anonymous said...

To the people complaining about SQL Injections, that is NOT the point of this tutorial. Someone who's looking into doing something like these should hopefully already have an idea on what SQL Injections are and how to avoid them (with that being said, it probably would be a good idea for the author of this article to put a NOTE or warning or something to novice coders looking for a quick copy and paste solution).

Bravo to the articles, this site is always consistent with usable and quick tutorials.

AE said...

How to change regular expression to accept Unicode search keywords ?

var start=/@/ig; // @ Match
var word=/@(\w+)/ig; //@abc Match

Anyone? Thank you in advance for the assistance.

desup said...

i have got problem, it will automatically add
before the name... and i dont know why...
But .. Awsome!! Thankssss

Anonymous said...

I have two doubts:
1. How can i tag multiple friends?
2. how can i close and stop the searching when sample text is entered?

hendra said...

i want to ask about regex condition when i'm write an email text?
such as test@yahoo.com

i try to make this exception but i cant

please help me

hendra said...

i check in error browser

in go.length:
"Uncaught TypeError:Cannot read property 'length' of null (repeater 15 times)"
and
in name.length:
"Uncaught TypeError:Cannot read property 'length' of null (repeater 2 times)"

can it fixed?

Anonymous said...

how to create facebook style next previous image popup with comment content? please help me..

Dzikri Aditya Darmawan said...

How to change the div into textarea??

Anonymous said...

what is the use for prefix in the config? thanks folks.

Anonymous said...

I am having a problem with the dropdown why is it that I can't use the arrow keys? how can i use the arrow keys instead of the mouse to select?

Anonymous said...

I have the same question like Dzikri Aditya Darmawan. Please answer me. :)

tom said...

Seriously how do we submit this via a form otherwise it's a little bit pointless?

Any guides would be AWESOME!

benhard said...

Owesome tut

Anonymous said...

The dropdown is to be focused when we type something in the textarea. the dropdown should be navigated with arrow keys like in facebook. it is not working like facebook status tagging. can you please any one help me out in this

sez said...

any update to this code now that they no longer use the @ for linking? great job, thanks so much.

Anonymous said...

nice bro........

Andre Chavez said...

excellent contribution friend would like to know how to work it and send me the contents of that div to a php process


sorry for my lenguaje, not speak ingles

Liquid Rubber said...

Nice post thank a lot for posting

Anonymous said...

How to change the div into textarea??

mohnish said...

Can you post it for image tagging also.......

Anonymous said...

How to change the div into textarea? after post insert db? srinivas

Luiz Karki said...

hey it repeats
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\tagfriends\boxsearch.php on line 9

what can i do.

Dr.Overlay said...

Hello, nice to visit your blog! Very good what you do! A query, is there any possibility of adding labeling of a person you get an email notificandotelo? Sorry for my English is very basic as I am starting my programming recently. Thank you very much.

serkan said...

Post?

Anonymous said...

You are genius Srinivas, you simplified my job

Anonymous said...

Hi is this possible in textarea? because it is not working for me... you use the "div" contenteditable="true" ..but when I use textarea.. it is not working..

Anu said...

This plugin is much easier https://github.com/astroanu/jquery-tag-a-friend2

Anonymous said...

The toturail is great... how we can implement navigation as in fb? it will be a great hint... hope u will ost that here... thanx.

Unknown said...

well is there a way to do facebook new method that is with capital character than @

Post a Comment