tags:

views:

130

answers:

2

Wow, this one has me tearing my hair out.

I'm tracking links in JQuery.

$(".hdr a[id]").mousedown(function(e){
    var h = this;
    var url = "/g/click/" + this.id;
    $.get(url);
  });

It appears that sometimes the browser beats the ajax call. The new page is loaded before the click tracker is fired. (It's not slow response time; the request doesn't even hit apache). This is intermittent and not readily reproducible, but it tends to appear after the user has been doing a lot on the site.

I used preventDefault in an earlier iteration of this, but that ends up breaking cmd-click and doesn't track right-clicks.

Is there a way to ensure this will run?

Thanks for all your help.

+2  A: 

Sounds like the same problem I was having when I asked: $.post() doesn't have time to run? The solution for me was to add the following into the mix:

$.ajaxSetup({async: false});

No longer doing asynchronous requests meant my items would finish before others would begin.

Jonathan Sampson
I ended up doing this, and it seems to have fixed the problem. Thanks!
Jason Butler
+1  A: 

If you are using a get request the response will be cached. To alleviate the cache issue you need to ensure that the url is unique. You can do this by either appending a unique dummy querystring item everytime to the url or better use the .ajax method and specify cache:false.

I would not use the asynch:false as this locks up the ui and if the response fails to come back or is delayed the user eventually has to crash out and would not solve the cached issue.

$(".hdr a[id]").mousedown(function(e){
    var url = "/g/click/" + this.id;
    $.ajax({
         url: url,
         cache: false,
         success: function(data){
                 //do something with the response
                 }
         });
});

N.B I may also be tempted to put a setTimeout call into your script. This will allow you to clear the timeout should another mousedown event occour in quick succession. This will prevent a flood of xhr requests being sent if the user mousedowns repeatedly.

redsquare