Possible Duplicate:
jQuery Ajax always returns “undefined”?
I'm trying to come up with a generic jquery ajax function which takes the url & parameters and returns the result. I'm trying to avoid using async:false
as it locks up the browser. If I use success
callback in the ajax call, the data returned is null due to the timing issue (success doesn't wait until the data is returned). If I use complete
, the persons
object is still null in the LoadPersons
method as it doesn't wait for the data to be returned from the ajax call. If place an alert(persons)
in the complete
callback, I get [object][Object]
so I'm getting the data back. How do I "fix" this issue? Am I talking sense? I would also ideally like to show a "loading.." image while it's doing this.
Here's my code -
<script type="text/javascript">
$(function() {
var persons;
var urlGetPersons = "Default.aspx/GetPersons";
LoadPersons();
function LoadPersons() {
persons = CallMethod(urlGetPersons, { });
if (persons != null) {
// do something with persons.
}
}
function CallMethod(url, parameters) {
var data;
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: function(result) {
data = result.d;
}, // use success?
complete: function(result) {
data = result.d;
} // or use complete?
});
return data;
}
});
</script>
This is what's comes to my mind with "generic" - but it's still asynchronous:
function CallMethod(url, parameters, successCallback) {
//show loading... image
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log('error');
}
});
}
CallMethod(url, pars, onSuccess);
function onSuccess(param) {
//remove loading... image
//do something with the response
}
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