How to track click on a link with ajax and javascript

I simply wanted to know on which links the user clicks. So I devised a method to capture these link URLS using javascript and posted them to server storing them in a log file.If this is what or something similar you would like to to do then read on.

This allowed me to see the user movement on my website with his IP address and time,I could capture his intenal and oubound kink clicks as well as clicks on the download link

The first step is to place a javascript function to on the link you want to capture

<a href="https://mysite.com/wp-content/uploads/2021/01/black-and-white-theme-preview.png" onclick="getUrl(this); return true;">Preview</a>

The javascript – place the following javascript on the head scetion of your page to track the link.This javascript will capture the link url and make ajax post to your server.How to handle the ajax on server will be explained later.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

function getUrl(e) {
   var href = e.getAttribute("href");
   //alert(href);
   $.ajax({
	  
	  type: 'POST',
	  data: {link: href},
	  
	});
}

</script>

The above script is assuming that the same php script on wgich the javascript is there is handling the post request,if that is not the case then above the type:’POST’,you can insert the url of the php as

url: 'path-to-php-script'
type: 'POST',
data: {link: href}

Now handling the ajax post is easy.go to your php file and place this code at the top of the file

if( isset($_POST['link']) ){
	
 write_analytic($_POST['link']);
 exit;
}
function write_analytic($text){
	
	$file_path= "some-path"."more-stats.log";
	$fp = fopen($file_path, 'a');//opens file in append mode
    
	date_default_timezone_set('Asia/Kolkata'); // CDT

	$current_date = date('d/m/Y--H:i:s');	
	fwrite($fp, "\n\n".$_SERVER['REMOTE_ADDR']."---".$current_date."---".$text);  
    
	fclose($fp);	
}



you will need to set the path to your log file.

The above code captures a link click and instanly posts to server by ajax and saves it to a log file.You can refreshe the log file to see the IP address, time and the link that was clicked.



That is all.

If you liked this article please do leave a reply and share it with friends.

Thanks.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.