javascript - Following link href after successful ajax call -
i've got normal link:
<a href="http://www.google.com" class="continue">continue</a> i've bound click event post ajax request 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 happen link followed on success....
ie, if there no error, user should redirected google.
i know can put window.location.href in success handler, trying avoid if possible
unfortunately (in case), ajax asynchronous, meaning click function starts ajax call , continues running without paying attention (and returns nothing @ end).
the success function called later (when ajax returns successfully) , different function, returning true has no bearing on original click function.
all say, need use javascript override anchor tag's natural behavior (go directly google.com) , happens afterward (redirect).
$('.continue').click(function (e) { e.preventdefault(); // otherwise, won't wait ajax response $link = $(this); // because '$(this)' out of scope in 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'); } }); });
Comments
Post a Comment