So a while ago I needed a custom click counter, to keep track of clicks and statistics for clients. As usual I googled first, just to realise there are some really crappy counters out there. As a result, I decided to make one myself using AJAX and it has been working flawlessly after some touches here and there.
I decided to load a php page, located somewhere else, which keeps track of the clicks through some basic GETs, no rocket science here.
if (isset($_GET['click']))
{
$link_name = $_GET['click'];
$uid = $_GET['uid'];
//includes databases settings and the variable $table, which is the name of your mysql table
include('settings.php');
$createTable = "
CREATE TABLE IF NOT EXISTS $table (
`id` int(11) NOT NULL auto_increment,
`name` text NOT NULL,
`ip` text NOT NULL,
`uid` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0
";
mysql_query($createTable) or die(mysql_error());
$link_name = mysql_real_escape_string($link_name);
$uid = mysql_real_escape_string($uid);
$ip = getenv('REMOTE_ADDR');
$query = "INSERT INTO $table (name, ip, uid) VALUES ('$link_name', '$ip', '$uid')";
mysql_query($query) or die(mysql_error());
exit("1");
} else { echo "Not a valid click"; }
Now to make some javascript that actually loads the page. I put the php code in ‘stats/stats.php’.
var req = false;
function loadXMLDoc(dname, func) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
}
else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange=function() {
if (xhttp.readyState==4 && xhttp.status==200) {
func.call();
}
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
function gotoUrl(url) {
window.parent.location = url;
}
function countClick(name, uid, gotourl) {
url = 'stats/stats.php?click=' + name + '&uid=' + uid;
func = gotoUrl(gotourl);
//alert(url);
loadXMLDoc(url, func);
}
Pretty basic, just call the function countClick when clicking on something in the HTML and you’re off to go. Be sure to give each clickable object an unique name. I added in the ‘uid’ identifier for own convenience, I use it to keep track of the clicks of all separate users.
I even added in a ‘countClickFunc’ for convenience, in case I need to call a function instead of redirecting to an url. Here’s an example of the HTML code:
<a onclick="countClick('testbutton', '1', 'http://www.exasm.net')">testbutton</a>
Now I know this is not perfect, but bear with me that these are just the basics, if you don’t trust your users, make sure to put some kind of anti-spam on the php script for example.


