0

I have a problem with this function

function readComm(){
    $.post("something.php", {read:"read"}, function(data){
        retVal = $.trim(data).toString();
        console.log(retVal);
        return retVal;
    });
}

It should call php file, and read some value from a text file. It does that as it should, and prints it on my console correctly, from a function. The problem is when I want to use that value in another function. It says that the value is undefined. retVal is a global variable, so that's not a problem.

Does anyone have an idea what could be the problem?

Jon Nylander
  • 8,743
  • 5
  • 34
  • 45
  • 4
    `$.post()` is asynchronous by default. Perhaps you are trying to use the value of `retVal` before it is set in the above callback. – techfoobar Feb 20 '14 at 09:57
  • 2
    This looks like yet another dup of http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Feb 20 '14 at 09:58
  • I've managed to solve this issue by calling a different function from inside of post function. And that is the only way to transfer that value to another function. Thank you anyway!!! – user3332054 Feb 20 '14 at 13:36

2 Answers2

1

You should change your angle to using callback functions approach, because what you do with $.post is asynchronous:

function readComm(callback){
    $.post("something.php", {read:"read"}, function(data){
        retVal = $.trim(data).toString();
        console.log(retVal);
        callback(retVal);
    });
}

function nextStep(retVal){
    alert(retVal);
}
readComm(nextStep);

what it does is actually taking the next step using nextStep callback function.

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
0

If you're doing something like this:

readComm();
alert(retVal);

Then that won't work because readComm is an asynchronous function. Anything that relies on the retVal MUST be either inside that function, called by it, or sufficiently deferred (for instance, a function called by an element that is only added by the asynchronous call)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592