I have this jquery call to ajax,
function findTaxForProcess(argPrc, argPrcAmount, argPrcDiscount) {
if (argPrc == '') { return 0; };
var _valToReturn;
if ($('#hdnTaxBefore').val() == "true") {
// if tax is calculated before discount
$.ajax({
url: '/AutoComplete.asmx/FindProcessTax',
type: 'POST',
timeout: 5000,
datatype: 'xml',
cache: false,
data: 'argProcess=' + argPrc + '&argAmt=' + argPrcAmount,
success: function (response) {
_valToReturn = $(response).find('double').text();
alert(_valToReturn);
}
});
}
else {
// the tax is calculated after discount
$.ajax({
url: '/AutoComplete.asmx/FindProcessTaxAter',
type: 'POST',
timeout: 5000,
datatype: 'xml',
cache: false,
data: 'argProcess=' + argPrc + '&argAmt=' + argPrcAmount + '&argDiscount=' + argPrcDiscount,
success: function (response) {
_valToReturn = $(response).find('double').text();
alert(_valToReturn);
}
});
}
alert('came here ' + _valToReturn);
return _valToReturn;
};
The problem is first alert shows 2.873 (in the else case, it shows 2.178), but the problem is second alert, the second alert shows , came here undefined??? FTW? what the hack is going wrong? I’ve been messing around this for 2 days but nothing!
Why is the value of _valToReturn undefined at second alert? and defined at first? any help?
EDIT : The alert came here _valToReturn is executing after the first alert. So, as (almost!) all answerer said that if its coming before, it would be undefined, I know that, but as I said it is executing after not before.
Ajax is an asynchronous request. By the time the success event executes, the alert “came here undefined” would have executed. And the variable has not been initialized by then.
Update:
In answer to your question looking closely, I believe
The anonymous function sees valToReturn as a local variable. Hence those variables are on a different “stack” if you will.
See this:
Javascript anonymous function not updating global variable
Or
Using variable outside of ajax callback function
Similar to yours.