Last updated on May 25th, 2022 at 10:37 am

This tutorial shows how to track your vistors click using simple php and Ajax. To implement the click tracking tool we need to create 2 files:

Demo.html: This file contains the html with the links and the Ajax code.
clickTracker.php: This files will be called by Ajax and records the click event.

DEMO.HTML will look like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ajax click tracking example</title>
<script>
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Implement business logic
function doTrack(element){
httpObject = getHTTPObject();
if (httpObject != null) {
dst = element.href;
src = document.location.href;
httpObject.open("GET", "clickTracker.php?src="+src+"&dst="+dst, true);
httpObject.send();
httpObject.onreadystatechange=function()
  {
  if (httpObject.readyState==4 && httpObject.status==200)
    {
	    window.location.href = dst;
    }

  }
}
}
</script>
</head>
<body>
<a href="" onclick="doTrack('https://mistonline.in');return false" > Test Click </a>
</body>
</html>

As you can see the destination URL have been added to the function doTrack() as shown above. Replace that with the URL of your choice.

Next step is to create clickTracker.php file

<?php
$src = isset($_GET['src']) ? $_GET['src'] : "-";
$dst = isset($_GET['dst']) ? $_GET['dst'] : "-";
$f = fopen('clickReport.txt',"a+");
$timestamp=date('Y-m-d H:i:s');
fwrite ($f,"Click Tracked :-> ".$src." : ".$dst." : ".$timestamp);
fwrite ($f, "\n");
fclose($f);
?>


We will write data dynamically using AJAX to a simple text file, If you are not sure how to read/write data usinga text file in php then GO HERE

Don’t forget to create a file with name clickReport.txt. Also make sure clickReport.txt has the sufficient permission for the Apache/Nginx/ PHP fpm process to write.

Now you can track timestamp of your website clicks.

Demo

Some bugs fixed and Demo added on May 25, 2022

6 thoughts on “Simple Ajax with PHP click tracker”
    1. Hello Sibo,

      Please make sure you create txt file before running the script. This script doesn’t have the ability to create the text file. Please let me know if you still face any issues.

Leave a Reply

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