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="" 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=""></script>

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


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']) ){
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);  

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.


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.