Tuesday 22 January 2013

Create a like button just like facebook !!


Facebook Like Button


Hullo there guys , today i'm gonna give you a step by step tutorial for creating a like button using php/jquery , much like facebook !! So what is the general algorithm that is to be followed ? It's quite simple :-

When a user presses the like button two things should happen :- One , the number of likes should be updated in the database and two , the changes should be communicated to the the front-end that is the number of likes which all the other users are seeing , should be dynamically updated without affecting other page contents .

So how to acheive this ?

First create a mysql table called likes like the following :-

Item_Number   |    Likes
--------------------------

item number is the serial number for the item(post/image/link etc) for which the number of likes are stored in the corresponding column . Now create a php file with the following contents :-

Like.php  (This file will give us the number of likes)

<?php
if(isset($_REQUEST['item_number']))
{
$x = $_REQUEST['item_number'] ;
$connection = mysql_connect("hostname","username","password");
$query = "SELECT * from database_name.likes WHERE Item_Number='{$x}' LIMIT 1";
$result = mysql_query($query);
$r = mysql_fetch_array($result);
echo $r["Likes"];
}
else if(isset($_REQUEST['add']))
{

$x = $_REQUEST['add'] ;
$connection = mysql_connect("hostname","username","password");
$query = "UPDATE Likes SET Likes=Likes+1 from database_name.likes WHERE Item_Number='{$x}'";
$result = mysql_query($query);

}
?>


Now , go to the file which will display the number of likes in real-time . suppose you want to display the number of likes in a div with an id "number_of_likes" , then the following jquery code will help you update the number of likes in real time :-


$(document).ready(function(){
setInterval(function(){
var item_number = 2 ; //say
var request_url = "Like.php?item_number="+item_number; //Build the request url
$.get(request_url,function(res){ $("#number_of_likes").html(res); })
},500)

//Other javascript/jquery code

$("#add").click(function(){

var item_number = 2 ; //say
var request_url = "Like.php?add="+item_number; //Build the request url
$.get(request_url,function(res){ $("#number_of_likes").html(res); })

})

});


So how does the code work ?
 The setInterval function takes in two parameters , the function to be executed and the number of milliseconds after which it'll be executed again and again , so basically what it does is it runs the function at an interval of every 500 milli-seconds  . So what does this function do ? The function basically fetches the contents of the file like.php?item_number=itemno after an interval of 500 milliseconds !! And what does Like.php contain ?? It contains the number of like sfor that particular item number !! So what does the script do then ? Yes it updates the number of likes every 0.5 seconds (1second = 1000 milli-second) , so eureka !! We're Done !!

The add button works in a similar way , just that we invoke it only when an user clicks the like button instead of repeating it !!


Creating the Buton

Just create a button and give it an id of "add"  !!


88 comments:

  1. Hi Anurag,

    Superb stuff to boost the social rankings of a website/blog. Facebook & twitter need to be optimized properly for the website to gain traction and visitors. This simple tweak can make a lot of difference to the number of visitors and the social sharing as well.
    Thanks for sharing this :)

    Do check out my entry for Get Published.

    Regards

    Jay
    My Blog | My Entry to Indiblogger Get Published

    ReplyDelete
  2. Hi Anurag,

    Thank for the tutorial. Is it efficient to call "like.php" and query the database every half second? Have you discovered another way to solve this problem?

    Thanks!

    ReplyDelete
  3. For efficiency , you can use something like memcached on the server side .. you can optimize your queries .. also you can increase the time interval .. Another option may be to store the number of likes for each seperate posts in seperate xml files (a file is created for each user , and there will be a tag for each post) .. then only that much part is queried instead of going through the entire database .. Also nosql solutions might be used , and you can create collections corresponding to a single user .

    ReplyDelete
  4. hi, just looking at this. exactly what im after although im a bit of a php/mysql newbie. when you create the table in your db do i just name it 'Likes'? or 'Item_Number | Likes' ?

    I'm a bit unsure about where the Item_Number bit fits in?

    ReplyDelete
    Replies
    1. Create something like this :-

      Id | Likes
      -------------

      Where id is a primary key . And likes is the number of likes for that particular item.

      If you have user accounts , then to track like from each account , you can have something like

      serial | post_id | user_id

      Delete
  5. Pleasr tell me how to create likes and item_number table

    ReplyDelete
  6. Wonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!

    MongoDB Training Centers in Chenai

    ReplyDelete
  7. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Microsoft azure training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  8. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  9. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating!!
    Artificial Intelligence Course

    ReplyDelete
  10. Thank for sharing this information, its really helpfull.
    For those who are looking for AI training in Bangalore, Visit:
    Artificial Intelligence training in Banhgalore

    ReplyDelete
  11. Post is very useful. Thank you, this useful information.

    Softgen Infotech is a leading training institute for all kind of the Best Software Training in Bangalore with real-time experienced trainers with 100% Placement Assistance.

    ReplyDelete
  12. Kim Ravida is a lifestyle and business coach who helps women in business take powerful money actions and make solid, productiveIamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder IamLinkfeeder

    ReplyDelete
  13. Theodore Hall (Ted) is a retired manufacturing executive who has gotten into Internet Marketing कल्याण मटका रिजल्ट Kalyan matka Satta Result

    ReplyDelete
  14. Annabelle loves to write and has been doing so for many years.meri recipe indnewstv fullinhindi buy seo service

    ReplyDelete
  15. Nama : Adi Mulia
    Email : rekayasateknologi@uhamka.ac.id
    Website : https://journal.uhamka.ac.id/index.php/rektek/index
    Thankyou for nice information

    ReplyDelete
  16. Nama : Adi Mulia
    Email : adimulia@uhamka.ac.id
    Website : https://uhamka.ac.id
    Thankyou for nice information

    ReplyDelete
  17. Tired of sharing long, nasty URLs? This app immediately shortens URLsCRYPTO NEWS 24X7

    ReplyDelete
  18. Great post. keep sharing such a worthy information.
    Web Designing Course In Chennai

    ReplyDelete
  19. Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article. data scientist course in kanpur

    ReplyDelete
  20. Cell style yes can. During game relationship central.insightminutes.com

    ReplyDelete
  21. Foreign time attorney why know my. Me pull have sign.insightminutes.com

    ReplyDelete
  22. Skin region its article early at walk fly. Mouth blue government truth.insightminutes.com

    ReplyDelete
  23. White mother area leave political foot skin oil. Team compare see response prepare manager. Before ago sport example movie claim.insightminutes.com

    ReplyDelete
  24. Hot machine white more quality opportunity. Discuss policy worry name loss of. Business student forward recognize.

    ReplyDelete
  25. Remain former alone bed. Letter model prove firm generation street everybody. Until music reveal through along account down effect.career-news

    ReplyDelete
  26. href="https://istanbulolala.biz/">https://istanbulolala.biz/
    NQLX

    ReplyDelete