Reputation:
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?
Upvotes: 2
Views: 3408
Reputation: 7026
use the build in ajax callbacks from jquery.
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
Upvotes: 0
Reputation: 2776
You could set async to false but better practice to use callback:
.done(function( success) {
if (success) {
doSomeThingElseNow();
}
});
Upvotes: 1
Reputation: 16460
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.
Upvotes: 9