I need a hyperlink to execute an Ajax call, and when that has completed, do the standard action for the hyperlink.
<a href="afterwards.html" target="_blank" onclick="return CallFirst();">Link</a>
The javascript function calls $.ajax(), waits for success or failure, then returns true.
function CallFirst()
{
$deferred = $.ajax({
type: "POST",
url: url,
data: data
});
// **todo** WAIT until the Ajax call has responded.
// Return true, which makes the <a> tag do it's standard action
return true;
}
The code must wait for $.ajax to succeed, then return true from CallFirst().
$deferred.when() terminates immediately. How can it be made to wait?
Just set async property to false
$deferred = $.ajax({
type: "POST",
url: url,
data: data,
async: false
});
But it is really a better idea to use callbacks.
You could set async to false but better practice to use callback:
.done(function( success) {
if (success) {
doSomeThingElseNow();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With