Sunday 14 April 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...