user103219 user103219 - 1 year ago 58
Javascript Question

Using new Image().src for click tracking

I am attempting to figure out why this click tracker isn't working. The code was written by another developer so I am not entirely sure if this ever did work.

function trackSponsor(o, p) {
(new Image()).src = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
return false;

From what I can gather is that when this function is called it 'creates a new image' to fire a php script asynchronously. According to Firebug, the request is made however it is 'aborted' ~30ms in. The odd thing is that it will 'sometimes' work as in 1 in every 10+ regardless of the browser.

I would much rather fix this so that it works instead of re-writing it as an ajax request.

Any help is appreciated.

Thanks in advance.


Because of tvanfosson's post that got me thinking. I have included the line which calls the click tracker below.

<a onclick="trackSponsor(60, 15077); goToNextStep(1988, 15077, 0); return false;" href="#">view</a>

the goToNextStep() actually changes the page. I am under the impression that it would only be executed after trackSponsor() had finished.

Answer Source

It's actually pretty trivial to rewrite as a get request using jQuery. Rewriting it will certainly help the next developer understand what's happening and might fix your problem. I'd need to know more about the contents of the variables -- perhaps they need to be urlEncoded? -- before I could help you any more on it. You might try urlEncoding them and see what happens.

function trackSponsor(o, p) {
    var url = PATH_BASE + 'click/' + p + '/' + o + "?_cache=" + (+(new Date()));
    return false; 

EDIT: you might want to check that another handler isn't redirecting the browser to a new location when the event triggering the tracking is invoked. This would abort any pending requests on the page -- and might allow a few to succeed based on the timing of the requests and if the results are delivered before the page is unloaded.