Reputation: 485
I have a jquery + ajax code to tracking click for ad links on my website. This is for testing purpose:
$(document).ready(function(){
$(".myadlinks").on("click",function(e){
e.preventDefault();
var d = {id:$(this).attr('id')};
$.ajax({
type : 'GET',
url : "adlinktracking.php",
data : d,
success : function(responseText){
if(responseText==1){
alert('click is saved OK');
window.location.href = $(this).attr('href');
}else if(responseText==0){
alert('click can't be saved.');
}
else{
alert('error with your php code');
}
}
});
});
});
When I click on an ad link, it show the alert: Click is saved OK but then It won't redirect to the expected url. I think there is something wrong with this line of code window.location.href = $(this).attr('href');
. Because When i tried to replace $(this).attr('href');
with "http://www.google.com". It works.
Please help... many thanks
Upvotes: 0
Views: 2846
Reputation: 5222
$(this)
not points to the link in the context of success callback. you have to set it in seprate variable and use it in success callback. check the following code.
$(document).ready(function(){
$(".myadlinks").on("click",function(e){
e.preventDefault();
var currentobj = this;
var d = {id:$(this).attr('id')};
$.ajax({
type : 'GET',
url : "adlinktracking.php",
data : d,
success : function(responseText){
if(responseText==1){
alert('click is saved OK');
window.location.href = $(currentobj).attr('href');
}else if(responseText==0){
alert('click can't be saved.');
}
else{
alert('error with your php code');
}
}
});
});
});
Upvotes: 1
Reputation: 6279
You need to have a reference to the href
attribute not in the callback. $(this)
in the call back is not the link a user has clicked.
$(document).ready(function(){
$(".myadlinks").on("click",function(e){
e.preventDefault();
var link = $(this);
var linkHref = link.attr('href'); //this line is new
var d = {id: link.attr('id')};
$.ajax({
type : 'GET',
url : "adlinktracking.php",
data : d,
success : function(responseText){
if(responseText==1){
alert('click is saved OK');
window.location.href = linkHref; //reference to the save href
} else if(responseText==0){
alert('click can't be saved.');
} else{
alert('error with your php code');
}
}
});
});
});
Upvotes: 4