I've got a click tracking AJAX function (calls a WebMethod
on an .aspx
page), and I need to call it when the user clicks through to a link.
Unfortunately, I'm using window.location = "newUrl"
to change the page, which seems to make the AJAX call fail. Is there a way around this?
I do not need to get any information back from the AJAX call, I just need to make sure the WebMethod
is called.
I'm aware that I could just redirect on the success()
or failure()
calls, but then I would have to wait for the clickTracking()
method to run, which takes ~ 1s
. That is not acceptable by the agreement in the project spec, and so is not a viable solution.
Instead of using AJAX, why don't you just send the user to an ASPX page that records the click and then sends the location
header to redirect to the new url? For instance, on link click, the following would occur:
window.location = "/redirect.aspx?track=true&url=" + encodeURIComponent(newUrl);
redirect.aspx
would then handle both the tracking and the redirecting to the new URL. That's pretty much the only way you can do it without waiting for an AJAX request to complete before sending the user on their way.
See also: Redirecting Users to Another Page (MSDN)
It's probably worth noting that you see this method every day on many sites. Most commonly, they are found in ads. An AdSense ad link looks like this:
http://www.google.com/aclk
?sa=L&ai=C6DnFKnl1S5zhKoSBjAeqyKzKBPOD_2ehlIXfD9WsvQsQAVDQzK______
8BYLvOuYPQCsgBAaoEGU_Q8k4OJin9jMDXAD6KQ_2Dsv7xyokLxRY
&num=1&ggladgrp=13269254452699041863&gglcreat=8511532373602616220
&sig=AGiWqtwzFm2sTimBuQpkD5kazyRNkkqH3w
&q=http://www.amazon.co.uk/s/%3Fie%3DUTF8%26keywords%3Dhello%2Bworld
ish, anyway (I knocked it down a bit). When you click it, you land at http://www.google.com/aclk, which redirects you to the end site after tracking the click.