FIXED! THANKS! See “Corrected Code” below.
The goal is to get data back from the dialog box. I have seen lots of articles, but could not get any of them to work, so I decided to use a web service to pass the data back and forth between the dialog box and the underlying page.
All of the code is in place except the code that reads values coming back from the web service. I can see in the debugger that the data is being passed back, but when I return to the caller, the returned data is undefined.
jQuery function getLocal calls AJAX, gets good data back, but when it returns to the function that calls it (verbListShow), the returned value is “undefined”.
This is all happening in an ASP.NET page that is written largely in jQuery, and opens a jQuery dialog box.
function getLocal(name) {
$.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;
return rtn;
}
});
}
The above code works, but when called, rtn is undefined. Here is the caller:
function verbListShow(dutyNumber) {
$('#dlgDutyList').dialog({
modal: true,
show: "slide",
width: 250,
height: 250,
open: function (event, ui) {
setLocal("DUTYNUMBER", dutyNumber);
},
buttons: {
"Select": function () {
var id = getLocal("VERBID"); // <*** Returns undefined
var verb = getLocal("VERB"); // <*** Returns undefined
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/SetDuty",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ dutyNum: dutyNumber, id: id, verb: 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);
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#dlgDutyList').dialog('open');
FIXED CODE:
function getLocal(name) {
var rtn = "";
$.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) {
rtn = data.d;
}
});
return rtn;
}
It defeats the purpose of AJAX to use it synchronously (AJAX stands for Asynchronous Javascript And Xml).
Now you cannot
returna value from the success method, but you can store it in a variable and then return thatBut the proper way would be to use a deferred object
and call it