jQuery Return value undefined
It defeats the purpose of AJAX to use it synchronously (AJAX stands for Asynchronous Javascript And Xml).
Now you cannot return
a value from the success method, but you can store it in a variable and then return that
function getLocal(name) {
var returnValue;
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
returnValue = data.d;
}
});
return returnValue;
}
But the proper way would be to use a deferred object
function getLocal(name, resultset) {
return $.ajax({
type: "POST",
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
resultset[name] = data.d;
}
});
}
and call it
"Select": function() {
var results = {};
var self = this;
$.when(getLocal("VERBID", results), getLocal("VERB", results)).then(function(){
$.ajax({
type: "POST",
url: "WebServices/FLSAService.asmx/SetDuty",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
dutyNum: dutyNumber,
id: results.VERBID,
verb: results.VERB
}),
success: function(data) {
data = $.parseJSON(data.d);
if (data.ErrorFound) {
showMessage(data.ErrorMessage, 2, true);
}
else {
log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("updateDuty: " + XMLHttpRequest.responseText);
}
});
}).always(function(){
$(self).dialog("close");
});
}
Everything is because $.ajax function don't return any value because of it's asynchronous behaviour, my advice is to make second parameter for getLocal
method called "callback".
Proper way is to do it like so:
function getLocal(name, callback) {
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
var rtn = data.d;
callback(rtn);
}
});
}
Then, your main code have to look like that (asynchronous code):
//some code here
buttons: {
"Select": function () {
getLocal("VERBID", function(id) {
getLocal("VERB", function(verb) {
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/SetDuty",
dataType: 'json',
//some code here
});
});
//some code here
To improve this code, to make two asynchronous calls at once, you can use jQuery Deferred object, and run .resolve(data)
on it just after all ajax calls obtained proper response.