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;
    });
}

      

+2


source to share


5 answers


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
}

      

+6


source


Peter is absolutely correct, but you can make the $ .ajax method work synchronously by passing async: false

.



+2


source


The problem is you are returning i

outside of the callback function. Basically, when you return i

, its content doesn't exist yet and won't exist until the server returns the data to your callback function.

+1


source


try it

function GetTotalSize(callback) {    
  $.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(outputData) {
       callback(outputData);
    });
}

function DoSomething(data)
{
   //....
}

GetTotalSize(DoSomething);

      

+1


source


I realize this is an older post, but it would be for me to use complete:[delegate]

instead success

. This ensures completion callback

.

0


source







All Articles