Generally I use only Google Analytics for the stats of my web apps, but for one of my current projects (Bröllopia – sökmotorn för ditt bröllop – a swedish wedding site) I needed a bit more. I wanted to have detailed statistics for links leading to other sites to use these stats in the app itself. One way of doing this is of course to make all these links go to a page on my site and then when this page loads I record all the stats I want and then redirects to the external site, for example the link www.digitalistic.com/tracker.php?id=123 loads tracker.php and logs a click on the link with the id “123” (this id needs to be mapped to a link in the database) and then forwards to www.webhostninja.com. The link on my site would then look like this:
<a href='http://www.digitalistic.com/tracker.php?id=123'>WebHostNinja</a>
The problems with this is that it is slow (one more page load) and that the link the user sees does not lead to the page, ie the link text “WebHostNinja” and then the user expects the link to be something like “http://www.webhostninja.com” and nothing else. I don’t like this from a usability point of view. Not that I have any evidence for it, but I suspect that relevant outgoing links help the sites Google juice. Definitly it helps the Page Rank of the site I link to, and why should I not help them?
My solution is to use some jQuery magic. Download and install jQuery (btw, if you like jQuery, then take a look at the fantastic jQuery tools). Then add the class “track_this_link” to each link tag that you want to track as well as give each link tag an unique id (so you can track which link is which). The href attribute should point to the external site directly and not to some internal page. The link above would now look like this:
<a href='http://www.webhostninja.com' id='123' class='track_this_link'>WebHostNinja</a>
Next step is to add a some javascript that adds an onClick event to all the links with the class “external_link”:
$(document).ready(function(){
$('a.track_this_link').click(function() {
$.post(http://www.digitalistic.com/tracker.php
, {id:this.id});
return true;
});
});
This means that each time an external link is clicked a post request is sent to digitalistic.com/tracker.php with a unique id for the link in question. What is left is to implement the tracker.php script so that it can handle the post and save the data you are interested in to the database in a secure and correct way. I am happy to just summarize the number of clicks per link on a daily basis, but if you want to save detailed data for each click.
Do you have a better solution to this problem? Let me know!