2

I have no idea what's going on here and was hoping someone could help, I'm sure it's something easy going on that I'm just missing.

I have a function in javascript that has a JQuery post inside of it. I would like to return the results of the post which is just text and put it in a variable. The number is coming back correctly from the Post but when I put it in the 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;
    });
}

5 Answers 5

6

You can't do it like that. Remember, the "A" in AJAX means "Asynchronous". The callback function you provide to $.post() will execute well after GetTotalSize() executes and returns.

You'll need to restructure 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 here's a possibility.

$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data)
{
  doSomethingWithTotalSize( data.toString() );
});

function doSomethingWithTotalSize( totalSize )
{
  // whatever
}
Sign up to request clarification or add additional context in comments.

Comments

2

Peter is absolutely right, but you can force the $.ajax method to work synchronously by passing async: false.

Comments

1

The problem is that you are returning i outside of the callback function. Basically when you return i, its contents don't exist yet, and won't exist until the server returns the data to your callback function.

1 Comment

Thanks for such a quick response! I tried your suggestion and updated my example code but I am still having the same problem, any other ideas?
1

Try this

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

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

GetTotalSize(DoSomething);

Comments

0

I realize this is an older post, but a solution for me was to use complete:[delegate] rather than success. This ensures that the callback is complete.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.