Jquery Ajax: value failed to return outside the success scope
I have a strange problem here (May be the silly one).
In the below code I declare the variable retVal and assigned null to it.
On the successful execution of code and I reassigned it with the return
value (msg.d).
It successfully show the value at alert(retVal + " divyansh"); but when I
tried the same at alert(retVal + " divyansh again"); I got null.
I know I can get the value by putting the "return retVal" inside the
success but I want to know why this happen and if there is way to return
the value at the bottom.
function getGrpParent() {
var retVal = null;
var hidType = $('[Id$=hidType]').val();
var hidGpId = $('[Id$=hidSelectedId]').val();
if (hidType == 'gp') {
var url = "../User/UserHierar.aspx/GetParentGroup";
var option = {
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url,
data: JSON.stringify({ GroupId: hidGpId }),
success: function (msg) {
if (msg.d != "") {
retVal = msg.d;
alert(retVal + " divyansh");
}
},
error: function (err) {
alert('error');
}
};
$.ajax(option);
}
alert(retVal + " divyansh again");
return retVal;
}
No comments:
Post a Comment