Reputation: 189
i got the following anchors to go to the target site and to track the user for stats:
<a href="http://target.tld" target="_blank" onclick="$('<img></img>').attr({src: 'stats.php?my_param=value'}); return true;">Foo</a>
<a href="http://target.tld" target="_self" onclick="$('<img></img>').attr({src: 'stats.php?my_param=value'}); return true;">Foo</a>
The first one generates a Status of 200 Ok for the img (_blank), but the status of the second one (_self) is (canceled).
Can someone tell me why, and is there a better way?
Thanks!
Upvotes: 0
Views: 1507
Reputation: 337560
First of all, avoid on*
event attributes. If you've got jQuery, use it to bind your events. Secondly, it looks like you're creating the img
element with the goal of making a GET request to track the click. Instead, just use jQuery to fire off the request.
<a href="http://target.tld" target="_blank" class="track-link" data-value="foo">Foo</a>
<a href="http://target.tld" target="_self" class="track-link" data-value="bar">Foo</a>
$('.track-link').click(function() {
var trackValue = $(this).data('value');
$.get('/stats.php', { my_param: trackValue });
});
Update
Try using the mousedown
event to ensure the request gets sent before the page transfers:
$('.track-link').mousedown(function() {
var $link = $(this);
if (!$link.data('request-sent')) {
$.get(
'/stats.php',
{ my_param: $link.data('value') },
function() {
$link.data('request-sent', true);
}
);
}
});
Update #3
$('.track-link').click(function(e) {
e.preventDefault();
var $link = $(this);
$.get(
'/stats.php',
{ my_param: $link.data('value') },
function() {
window.location.assign($link.prop('href'));
}
);
});
Upvotes: 1