Saturday 29 October 2016

JavaScript function that returns AJAX call data





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"); });




Source


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...