views:

43

answers:

1

I remember a couple of years a go, I used an hack from somewhere to update link hits in the background. What I remember is that I had an onclick event on my links that triggered a javascript function which tried to load an image or something (this is the hack), but instead of an image (or whatever it was) you put in an url like 'mysite.com/updatehits.php?id=3'

Hope this makes sense :S

+4  A: 

Say you have this link:

<a id="link" href="foo.html">Click for foo</a>

You want the user to visit that link, but transparently call a 'hit counter' via ajax. That can be done like so:

$("#link").click(function(e) {

    // prevent the link from getting visited, for the time being
    e.preventDefault();

    //update the counter
    $.post("counter.php" {incrementCounter: this.href}, function(resp) {
        if(resp == "success") { 
            alert("updated");
        } else {
            alert("failed");
        }
        // updated. Now visit this link as normal 
        window.location.href = this.href;        
    });
});

Still, I think counting views is something best done on the server side. Plus, this will more than likely cause an annoying perceptible delay to the user upon visiting links.

karim79
I'm actually using a Google Analytics based library that does approximately the same thing. I don't think you actually need the `e.preventDefault()`, though. This and the default should both run on click, with no problem. +1
Ryan Kinal
How do you propose counting link server side? What's the most common method for tracking clicks?
breez