Question

I need to track outbound clicks from a directory on our site, and would like to do this so that the actual url is in the href. Something like:

 <a href="http://www.example.com" id="a24" class="link" >Go to Example</a>

This is the JQuery I'm using below. The click.php file is basically looking up the link id and then inserting the click information into a mysql table.

This seems to work fine even if the click.php takes a long time to complete. In other words, the user immediately links through to the destination url, even if I set the the click.php to sleep for 10 seconds before completing.

I'm using $('a.link').mousedown instead of $('a.link').click When I use .click, then it doesn't work (the click is not recorded). I'm just curious why it wouldn't work with using the .click function and only works with the .mousedown function.

Is this a good way to capture the clicks with JQuery or is there a better way? (I realize that anyone with Javascript turned off wouldn't be counted).

$('a.link').mousedown( function(e){

        var my_id = $(this).attr('id');

        $.ajax({    
          type: "GET",
          url: "/tiger/sal/clicks/click.php?id=my_id"
        });

        return true;

});
Was it helpful?

Solution

You're not giving jQuery enough time to compute everything before your browser directs. Why don't you try something like:

$('a.link').click( function(e){

   // Prevent the browser from running away
   e.preventDefault();

   // I've changed this to POST to make it a bit more secure
   // You can access the link ID with $_POST['link_id'] now
   $.post('/tiger/sal/clicks/click.php', { link_id: $(this).attr('id') });

   // Wave goodbye
   window.location.href = $(this).attr('href');

});

OTHER TIPS

I don't see why it wouldn't work.

This works when I tested it but the url endpoint needs to be fixed in your AJAX call:

$(function(){
  $('a.link').click( function(e){
    var my_id = $(this).attr('id');
    var href = $(this).attr('href');
    $.ajax({    
      type: "GET",
      url: "/tiger/sal/clicks/click.php?id=" + my_id,
      success: function(d){
          // allow it to successfully call the server before redirecting.
          window.location = href;
      }
    });
    return false;
  });
});

I wouldn't do it in a "mousedown" since that doesn't guarantee that the user actually clicked on the link.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top