function test() {
var flag1 = false;
if ($('#field1').attr('value') || !$('#field1').attr('value')) {
$.ajaxSetup({
cache: false
});
$.getJSON("test_term.php", {
'term1': $("#cde").attr('value'),
'cd3': $("#cde3").attr('value')
}, function(data) {
if (data[0].stss == 'K') {
var status = data[0].stss;
flag1 = true;
} else if (data[0].stss == 'U' || data[0].stss == '') {
flag1 = false;
return;
}
});
}
alert("ANonymous value" + flag1);
return flag1;
}
How do I return the “flag1” value from the anonymous function used in getJson()?
It is always returning false which is being referred at the top.
This is not possible the way you try it.
Ajax calls are asynchronous, they return whenever they are ready to. The inner function you’ve passed to
getJSON()runs well after the outer functiontest()has finished running.That means – whatever you want to happen when the Ajax call returns – put it into the callback function. Do no work with flags and return values.
E.g.