I’m running into an issue with a jquery ajax function not properly returning its results back to a javascript if statement.
Here is the issue, we have a database function that is generating a long string of if/then statements, an excerpt of which is below
if(1==1 && (GenericAjaxValidation("System.Yes")=="Y")) {do stuff}
The 1==1 is the result of something that happened in the database, so just ignore that bit. The GenericAjaxValidation call is the piece that is giving us issues The javascript function that it calls is below.
function GenericAjaxValidation(token) {
$.ajax({
type: "Post",
url: '../FormAjax/GetAjaxValResult',
data: {TOKEN:token,FormId:formDisplay.FormID,FormLayoutId:formDisplay.FormLayoutID},
dataType: "json",
timeout: 30000,
async:false,
success: function(obj) {
result=obj.Object.ReturnValue;
},
error: function(obj) {
return false;
},
complete: function(){
return result;
}
});
}
The whole process is set up to fire off as part of an onchange event, and we reach the if statement with no issues. If I drop a break point into the jquery ajax function, it processes properly, and returns the “Y” that it is supposed to. However, when I step back out to the if statement, it fails. I looked at it a bit more and realized that it was always treating the result of GenericAjaxValidation as undefined. In fact, to test it, I changed the if statement to test for equality with undefined, and it succeeded.
My suspicion is that while the asynch: false is causing the rest of that single function to wait for the return, it doesn’t appear that the if statement is waiting on it, and evaluates without waiting for the actual value. I searched the net for about a half hour on this one trying to find anything that said for sure one way or the other, but my Google-Fu failed me today.
So, my question is this: is there a way to make this work? or does javascript simply not play nice with this process.
Try (untested code):
(edit: as @toby pointed out, the
completehandler is unnecessary and doesn’t do anything)The problem is that
GenericAjaxValidationwasn’t returning anything. It’s thecompletefunction that returns. A return only returns from the immediate function, not the enclosing function, soGenericAjaxValidationwas just completing without areturnTo make it more clear, your original code could be written to be functionally equivilent like this (note in this sample and your original code,
resultis a global variable)_:As you can see,
GenericAjaxValidationneverreturns anything.