I would like to create a JavaScript function which returns the value of a jQuery AJAX call. I would like something like this.
function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
},
success: function(data){
return data;
}
});
}
I know I can do this by setting async to false but I would rather not.
Answer
With jQuery 1.5, you can use the brand-new $.Deferred
feature, which is meant for exactly this.
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
No comments:
Post a Comment