How to capture links clicked by a user on your website?

You may like to know details about the links clicked by the users on your website to know the details of the traffic o your website. This article will describe in detail about capturing the users clicking links on your website. We shall do that using Ajax.

Inser the following code in the head section of your website

<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>

Now add the following code on the link on your website. Replace the link with the link of your website.

<a href="https://tambolatickets.in/page-board.html" onclick="getUrl(this); return true;" style="">Tambola Number Calling And Playing Board</a>

We shall now write the code on the server side to capture the data sent by the Ajax request. Insert the following code to the script which your forms posts data.

// ajax controller for capturing links
if( isset($_POST['link']) ){
	
 write_analytic($_POST['link']);
 exit;
}

Now write the following code in the php file on your server

function write_analytic($text){
	//global $path_to_theme;
	$file= "more-stats.txt";
	$fp = fopen($file, 'a');//opens file in append mode
    global $theme_background;
	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 can also use the function specifying user action on an input field in your form on your web page as under. Replace theme with the name value of the field on your input form

write_analytic("User Previewed through link theme - ".$_POST["theme"]);


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.