Sometimes you need to monitor the number of clicks on an HTML element such as an image, a button, or a hyperlink. You may define an onClick()
function to increment a count on each click event. This count can be updated on server-side using AJAX and PHP. The count can be stored in database against a unique reference for the element, page etc.
The below sample code demonstrates how to send click count using AJAX to the server. On the server, the PHP script update.php receieves the data and writes it to a text file. I am choosing text file for ease of demonstration. You may choose to store this in MySQL database instead.
AJAX
function onClick(e) { var id = e.getAttribute('data-pageref-id'); var post = 'id='+id; var req = new XMLHttpRequest(); req.open('POST', 'update.php', true); req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); req.onreadystatechange = function(){ if (req.readyState !== 4 || req.status !== 200) return; document.getElementById("clicks").innerHTML = req.responseText; }; req.send(post); }; <a href = "index.html" target="_blank" data-pageref-id="pageA1234" onClick="onClick(this)">LinkA</a> <p>Clicks: <div id="clicks"></div></p>
The data-pageref-id is a custom attribute (data-* are HTML5's custom attributes that allows you to store any custom data and refer it later using the attribute name). You can refer this inside onClick()
function. This is a unique reference for the element and the webpage.
The below PHP code update.php runs on the server to receive the click count and store it in a text file.
PHP
<?php //Set path to the text file that stores counts $file = 'click_data.txt'; //Open the file in read write mode $fh = fopen($file, 'r+'); //Assign the page referene posted from page to a variable $id = $_REQUEST['id']; //Initialize lines variable $lines = ''; //Repeat until end of file while(!feof($fh)){ //Split the line using comma delimiter $row = explode(',', fgets($fh)); $pageref = trim($row[0]); $count = trim($row[1]); if(!empty($pageref)){ if($pageref == $id){ //Increment count $count++; echo $count; } //Append new line to text file $lines .= "$pageref,$count\r\n"; } } file_put_contents($file, $lines); fclose($fh); ?>
The file click_data.txt stores data in the format data-pageref-id,count
. You have to initialize this file with initial count for each page and link.
pageA1234,0 pageB5678,0
The count will be updated each time the link is clicked.
To track an element on another page, you just need to reuse the same JavaScript, but put a different data-pageref-id for the element. Also add this pageref and initial count to the text file. As long as you are tracking only few links on few pages, you can use the flat text file based solution. If you have more complicated tracking requirements, it is better to store the counters in database.