jQuery Counting No of Clicks

You can count no of clicks in your web page using jQuery .click() function. This is helpful if you want to track no of downloads in your webpage or no of hits for an article etc. In this post i will demonstrate counting no of clicks using jQuery, PHP and MYSQL.

sql file

CREATE TABLE `increment` (  
`id` int(5) NOT NULL, 
`url` varchar(50) NOT NULL,
`count` int(10) NOT NULL,
 PRIMARY KEY (`id`)
) 
ENGINE=InnoDB DEFAULT CHARSET=latin1;

Once you create table, Insert 2~3 values.

increment.php

<?php
if(@$_POST['id'])
{
$id=$_POST['id'];
$db=mysql_connect('localhost','admin','1234');
mysql_select_db('test',$db);
$sql="SELECT * FROM increment WHERE id='$id'";
$result=mysql_query($sql,$db);
$row=mysql_fetch_array($result);
$count=$row['count'];
$count+=1;
$sql="UPDATE increment SET count='$count' WHERE id='$id'";
$result=mysql_query($sql,$db);
}
else
echo "Access Forbidden";
?>

increment.php takes id as input and increments count value of that particular id.

index.html

<html>
<head>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('.linklist').click(function(){
var linkid=$(this).attr('id');
$.post("increment.php", { id: linkid } );
});
});
</script>
<a href="http://www.yahoo.com" class="linklist" id="1">Yahoo</a>
<br/>
<a href="http://www.google.com" class="linklist" id="2">Google</a>
</body>
</html>

Please note specify individual id for each link. Specify id based on id value in your database table.

You Might Also Like