Javascript function with JQuery POST always returns undefined
I have no idea what is going on here and was hoping someone could help, I'm sure this is something lightweight that I'm just missing.
I have a function in javascript that has a JQuery column. I would like to return the results of a message that is just text and put it in a variable. The number is returned correctly from Post, but when I put it in a variable, the variable says "undefined". Any ideas?
var total = GetTotalSize();
alert(total);
function GetTotalSize(){
var i = "";
$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data){
i = data.toString();
return i;
});
}
source to share
You cannot do that. Remember, "A" in AJAX stands for "Asynchronous". The callback function you provide $.post()
will be executed upon completion and return GetTotalSize()
.
You will need to rebuild your code to accommodate this. I can't be specific in my recommendation because I don't know what the rest of your code looks like, but there is a possibility here.
$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data)
{
doSomethingWithTotalSize( data.toString() );
});
function doSomethingWithTotalSize( totalSize )
{
// whatever
}
source to share