Facebook Style Tag Friends with Jquery, Ajax and PHP
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
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


69 comments:

  1. pz tell me in xml not with config.php

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

    ReplyDelete
  3. Was that my request? :)

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

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

    ReplyDelete
  5. 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

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

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

    ReplyDelete
  8. This is Like magic..Nice one broh

    ReplyDelete
  9. its not work...why..

    ReplyDelete
  10. 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

    ReplyDelete
  11. 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.

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

    ReplyDelete
  13. 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.

    ReplyDelete
  14. Yes, Srinivas is absolutely right. Thanks Srinivas.

    ReplyDelete
  15. 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

    ReplyDelete
  16. NOT WORKING IN FIREFOX 3.6

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

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

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

    ReplyDelete
  20. 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..

    ReplyDelete
  21. 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...

    ReplyDelete
  22. 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.

    ReplyDelete
  23. But this is a div, how about a textarea?

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

    ReplyDelete
  25. 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

    ReplyDelete
  26. 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..

    ReplyDelete
  27. 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.

    ReplyDelete
  28. 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.

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

    ReplyDelete
  30. 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?

    ReplyDelete
  31. 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

    ReplyDelete
  32. 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?

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

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

    ReplyDelete
  35. 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?

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

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

    Any guides would be AWESOME!

    ReplyDelete
  38. 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

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

    ReplyDelete
  40. 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

    ReplyDelete
  41. How to change the div into textarea??

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

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

    ReplyDelete
  44. 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.

    ReplyDelete
  45. 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.

    ReplyDelete
  46. You are genius Srinivas, you simplified my job

    ReplyDelete
  47. 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..

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

    ReplyDelete
  49. 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.

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

    ReplyDelete
  51. can be implemented with a form? inside a textarea or input?

    ReplyDelete
  52. looks osm as u r..:) but i have a question i want to make tags stable through database connectivity. but i got no idea on this.could you please help me. :)

    ReplyDelete
  53. Not working.... need to polulate datbase first...

    ReplyDelete
  54. can i put it into textbox not div?

    ReplyDelete


  55. its not working with textarea please answer

    ReplyDelete
  56. i have modified it with text area. But due to the fact in the code login that is making old value blank. It is working only for one friend tag. Any idea will be welcome for making it for multiple tag in textarea.

    ReplyDelete
  57. if form is bottom position, after click user in list dropdown, it jump to Top page. How can i fix it ?Thanks

    ReplyDelete
  58. Hello
    Please why is it that we can not tag more two people and write a text without it being deformed ?

    ReplyDelete
  59. Hi,
    Is there a way we can implement this in Angularjs.

    ReplyDelete
  60. What a great job!9lessons is my elibrary

    ReplyDelete
  61. Hello Sir,
    I am big follower of yours.sir i need list of Tag like #RedsRugby from the facebook can you please help me?

    ReplyDelete

Make in India