Ajax Like Script Using PHP,MySQL and JQuery

This post define how to create ajax like script with JQuery, PHP and MySQL. using IP address to prevent the duplication.

First of all we will create the database tables.
















-- items table
CREATE TABLE IF NOT EXISTS `items` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `item` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;

-- likes table
CREATE TABLE IF NOT EXISTS `likes` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `ip` varchar(40) CHARACTER SET latin1 NOT NULL,
  `item_id` int(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

and we will insert some data to test it.













INSERT INTO `items` (`id`, `item`) VALUES
(1, 'Genteel women suppose that those things do not really exist about which it is impossible to talk in polite company. '),
(2, 'Behind all their personal vanity women themselves always have an impersonal contempt for woman.'),
(3, 'Ah women. They make the highs higher and the lows more frequent.'),
(4, 'Women are considered deep - why? Because one can never discover any bottom to them. Women are not even shallow.'),
(5, 'There is more wisdom in your body than in your deepest philosophy.'),
(6, 'Does wisdom perhaps appear on the earth as a raven which is inspired by the smell of carrion?'),
(7, 'There are various eyes. Even the Sphinx has eyes: and as a result there are various truths and as a result there is no truth.'),
(8, 'Mystical explanations are thought to be deep the truth is that they are not even shallow.'),
(9, 'In the consciousness of the truth he has perceived man now sees everywhere only the awfulness or the absurdity of existence and loathing seizes him.'),
(10, 'Words are but symbols for the relations of things to one another and to us nowhere do they touch upon absolute truth.');

 

in the php side we will create the index.php file which contains items to be liked.





























include('connect.php'); // connect to database
include('functions.php'); // needed functions
echo '<ul>';
// get the items from database
$sql = "SELECT * FROM items ORDER BY id ASC";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo '<li>';
// check if the user has liked this item before
if (check_ip($row['id'] 

,get_real_ip()) == 0) {
// if not liked before present the like button
echo '<a href="javascript:void();" class="like" id="'.$row['id'] .'">Like <span>'.likes($row['id'] 


).'</span></a>';
} else {
// if liked, deactivate the button
echo '<a href="javascript:void();" class="liked">Liked <span>'.likes($row['id'] 

).'</span></a>';
}
echo $row['item'] 

.'</li>';
}
echo '</ul>';

 

Notice that we have three functions in the previous code :

  • get_real_ip() : to get the user real ip not proxy
  • check_ip($item_id,$ip) : to check if this ip has liked this item or not
  • likes($item_id) : to consume the number of item likes

We should include the JQuery library in the index.php in order the script to work.



<script type="text/javascript" src="jquery.min.js"></script>

 

The JQuery function that is responsible for the like operation :
























$(function() {
$(".like").click(function() {
var item_id = $(this).attr("id");
$('a#'+item_id).removeClass('like');
$('a#'+item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: 'item_id='+item_id,
cache: false,
success: function(data){
if (data == 0) {
alert('you have liked this item before');
} else {
$('a#'+item_id).addClass('liked');
$('a#'+item_id).html(data);
}
}
});
return false;
});
});

 

Finally we will recieve the posted data and process it with PHP in ajax.php file.































include('connect.php');
include('functions.php');
if(isset($_POST)) {
$item_id = abs(intval($_POST['item_id'] 






















)); // recieve from index.php
$ip = get_real_ip();
// check if this user ip has liked this item or not
$query = mysql_query("SELECT * FROM likes WHERE item_id='$item_id' AND ip='$ip' LIMIT 1");
$check = mysql_num_rows($query);
if ($check == 0) {
// if not liked before insert the liked item ID and the user IP to database
$add = mysql_query("INSERT INTO likes (item_id,ip) VALUES ('$item_id','$ip')");
if ($add) {
// after adding the like (vote) to database, consume the number of item's likes
$check = mysql_query("SELECT item_id FROM likes WHERE item_id='$item_id'");
$number = mysql_num_rows($check);
sleep(1);
// return new number of item's likes instead of the current likes number.
echo 'Liked <span>'.$number.'</span>';
}
} else {
// if this user has liked the item before return 0 value
echo 0;
}
} else {
// if POST not isset return 0 value
echo 0;
}
Demo Download Ajax Like Script

Leave a Comment

Your email address will not be published. Required fields are marked *