Reputation: 515
I'm trying to use jQuery to count clicks, store them in a cookie and then echo them back out.
I've found some code online that allows me to do it, but I dont seem to be able to make it work. It's creating the cookie file and storing '0' in it, but it does not update on clicking of links. Any guidance as to whats going wrong with this code would be great. :
clickCount.js
jQuery(function(){
$("a").click(function{
var cookiename = 'linkcounter';
if($.cookie(cookiename) == null){
$.cookie(cookiename, 0);
}
$.cookie(cookiename, $.cookie(cookiename)+1);
});
});
index.php
<?php
session_start();
$counter_file = 'counter';
if(!file_exists($counter_file)){
file_put_contents($counter_file, 0);
}
$counts = (int)file_get_contents($counter_file);
file_put_contents($counter_file, $counts++);
// you can use $counts if you want to display it on the page.
?><!DOCTYPE html>
<html>
<head>
<title>Link Click Counter Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="countdetect.js"></script>
</head>
<body>
<a href="http://www.google.com/"></a><br />
<a href="<?php echo $_SERVER['PHP_SELF']; ?>"></a><br />
Link clicks: <?php echo $counts; ?>
</body>
</html>
Upvotes: 0
Views: 558
Reputation: 3625
In you PHP code, you're not storing the click count into a cookie, but into a file.
You either have to update the counter file by by making an AJAX request from your JavaScript to your server, or actually write a cookie within your PHP file:
<?php
$cookieName = 'linkcounter';
$count = isset($_COOKIE[$cookieName]) ? (int)$_COOKIE[$cookieName] : 0;
$count++;
setcookie($cookieName, $count);
?>
Link clicks: <?=$count?>
Make sure you use the same cookie name in both JavaScript and PHP.
Upvotes: 1