In last article, I made mention of Jquery used within Facebook. Today, I'll show you one of'em. That is "like button".
As you know, when our friends share something, we can like it easily. When clicked the like button, data is saved without refresh. Because of this is JQuery&Ajax. Actually this example is not going to be like Facebook Like Button Module exactly, but, may be a good idea to do it for some of us. This things're so easy to do. We all need a database, a PHP page and a coding ajax page with ajax library, where is that complex?
Let's start it!
First, create your MYSQL Table;
CREATE TABLE `jquery_app`.`LikeButton` ( `ID` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `data` VARCHAR( 255 ) NOT NULL )You shall need this files:
- settings.php //database configurations
- jquery.js //your jquery code
- jquery library //you must include this file on index.php page
- match.php //your php code that you do like something and write database
- index.php //default page
index.php
This is facebook like button example. This is what i share! :) < a href="#" id="like">Like < div id="whathappened"> //We see total clicked like button < /div> < div id="whathappening"> //We see what happening now < /div>
When click the link, sending query to jquery.js page. After that jquery starts ajax method and searchs match.php page for adding +1.
jquery.js
// JavaScript Document $(document).ready(function() { $('#like').click(function() { $('#whathappening').fadeIn(1000); var wait="Adding.."; $.ajax({ cache:false, async:false, url:'match.php', success:function(inc) { $('#whathappened').html(inc); $('#whathappening').html(wait); $('#whathappening').fadeOut(1000); } }); }); });
When id=like click, data'll been added to database. If you ask how to add this, you should analyze the page is shown below.
match.php
include("settings.php"); //adding data $random=rand(0,99999999); $ekle=mysql_query("INSERT INTO LikeButton(data) values('$random')"); //how many data we got //with the data we've just added $show=mysql_query("select * from LikeButton"); $total=mysql_num_rows($show); //Getting total liked echo "Total: ".$total; //Print total liked.
What you see here, all php code. We include settings.php page for connection database. We get total and add +1 to this.
settings.php
$conn=mysql_connect("localhost", "username", "password") or die("error1"); mysql_query("SET NAMES 'utf8'") or die("error2"); mysql_select_db("jquery_applications",$conn); error_reporting(0); ini_set('display_errors','Off'); error_reporting(E_ALL);
That's it! You've just done Facebook like module. If you want to see how to work this, you can visit the web site for demo.
Module view |
When "Like" link click |