Click Tracking or How Do I Track My Links?
In this tutorial you will learn how to track different user actions on the site using AJAX. It’s no longer the problem to know what the user doing.
Here you can find a few very useful solutions to track link clicking or whatever-action-you-want-to-track.
Basic solutions
This file was downloaded 739 times.
The first solution – to redeclare global default functions:
document.onclick = function(e) {
e = e || event;
var el = e.target || e.srcElement;
if (el.tagName=='A')
{
alert('The link was clicked');
}
}
Pretty simple, right?
Let’s improve it to make useful stats:
document.onclick = function(e) {
e = e || event;
var el = e.target || e.srcElement;
//el - clicked element
if (el.tagName=='A' && el.target=='_blank')
{
//Here we can send ajax response to our stat
//script to collect the outbound link anchors
SendResponse('stat.php', el.innerHTML);
/*Keep in mind - you can do whatever you want
with that data -
store time, referer, page name or other
details
You can even build click map of single page
or entier web-site*/
}
}
This solution works great in IE6-7, FF 1.5-2.0 and Opera 9
Another solution – dynamically add onclick events to target elements
Here’s the code:
function addEventListener(instance, eventName, listener) {
var listenerFn = listener;
if (instance.addEventListener)
{
instance.addEventListener(eventName, listenerFn, false);
} else if (instance.attachEvent)
{
listenerFn = function() {listener(window.event);}
instance.attachEvent("on" + eventName, listenerFn);
} else
{
throw new Error("Event registration not supported");
}
return
{
instance: instance,
name: eventName,
listener: listenerFn ;
}
}
function AddOnclickToAllLinks() {
for (i=0; i<document.links.length; i++)
{
//Check for outbound parameter - target
if (document.links[i].target == '_blank')
addEventListener(document.links[i],
"click",
function() {alert("You clicked me!");});
}
}
Let’s add onload=”AddOnclickToAllLinks();” to <body> tag.
You see – now you have onclicks on every outbound link.
Ok, let’s learn now how to implement this code and solutions in real tasks
Sample script : Collecting exit-pages
I’m sure you have hard-structured web-site, or may be not, anyway – some template system should be in use.
So the first step – is to paste .js library code to your output HTML
Don’t forget to save your Javascript code to independent file (in example js-code was saved to /js_library/ directory and named “tracker.js”)
It doesn’t matter what solution will you choose (first with onclick redeclare or second with dynamic onclick declare)
it should look like this:
……
<meta name=”robots” content=”index, follow” />
<script src=”/js_library/tracker.js” mce_src=”/js_library/tracker.js” type=”"></script>
</head>
……
Here’s what I’ve saved to .js file:
document.onclick = function(e){
e = e || event;
var el = e.target || e.srcElement;
if (el.tagName=='A' && el.target=='_blank')
{
makeRequest('stat.php');
}
}
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest)
{
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject)
{
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{}
}
}
if (!http_request)
{
return false;
}
http_request.onreadystatechange = function()
{};
http_request.open('GET', url, true);
http_request.send(null);
}
I’ve used the simplest way to send GET HTTP request (function makeRequest) – you are able to use your favourite AJAX-framework.
Collecting the stats on the server-side
The simpliest way – not to use any frameworks or classes, keep in mind – the more visitors you have – the more stats will collect your script. Be aware of server’s overload.
Mysql table
Create “stats” table in PhpMyAdmin or whatever you use to manage your MySql server.
CREATE TABLE `stats` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `ip` VARCHAR( 20 ) NOT NULL , `page` VARCHAR( 512 ) NOT NULL , `time` INT( 11 ) NOT NULL ) ENGINE = MYISAM ;
Now we have the table.
The next code is just a sample of tiny stats collector written on PHP:
<?php
//Config
$db_host = "localhost";
$db_user = "root";
$db_password = "";
$db_basename = "tracker";
$db_debug = false;
//Tiny DB-lib
include('lib_db.php');
//Connecting to DB
sql_establish();
//Current time
$tracker_time = time();
//Tracked page
$tracker_page = mysql_real_escape_string(
substr(getenv("HTTP_REFERER"), 0, 512));
//IP of the visitor
$tracker_ip = getenv("REMOTE_ADDR");
//Checking for double
$double_check = sql_first_query(
"SELECT id FROM stats WHERE ip = '$tracker_ip'
AND page = '$tracker_page'
AND time = $tracker_time");
if (!is_array($double_check) || empty($double_check))
{
//Inserting new query
sql_db_query("INSERT INTO stats
VALUES('', '$tracker_ip', '$tracker_page', $tracker_time)");
}
?>
That’s it!. You’ve just created a simple exit-page tracker.
P.S. For lazy guys
You can easily track your link by pasting onclick events on every link manually.
This file was downloaded 739 times.
Leave a Reply