Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  116] [ 2]  / answers: 1 / hits: 21805  / 11 Years ago, wed, may 15, 2013, 12:00:00

I've got a normal link:



<a href=http://www.google.com class=continue>Continue</a>


I've bound the click to an event to post an ajax request like this:



$('.continue').click(function () {

$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert(error - + err);
},
success: function () {
return true;
}
});
});


What I'm trying to get to happen is the link to be followed on success....

ie, if there is no error, user should be redirected to google.



I know I can put window.location.href in the success handler, but I was trying to avoid this if possible


More From » ajax

 Answers
1

Unfortunately (in your case), ajax is asynchronous, meaning that your click function starts the ajax call and then continues running without paying any attention to what it does (and thus returns nothing at the end).



The success function is called later (when the ajax returns successfully) and is a completely different function, so its returning true has no bearing on your original click function.



All this to say, you will need to use javascript to override the anchor tag's natural behavior (go directly to google.com) and what happens afterward (redirect).



$('.continue').click(function (e) {
e.preventDefault(); // otherwise, it won't wait for the ajax response
$link = $(this); // because '$(this)' will be out of scope in your callback

$.ajax({
type: 'POST',
url: '/url-to-post-to',
data: mydata,
contentType: 'application/json',
error: function (err) {
alert(error - + err);
},
success: function () {
window.location.href = $link.attr('href');
}
});
});

[#78222] Tuesday, May 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;