1

I have function:

function test(){
   $.post('data.php', function(val){
       return val;
   })

   return 'error';
}

and i use this simply:

console.log(test());

post is doing - return good value, but function test return me 'error' instead of value from data.php. Is possible get value from $.post? If yes, how?

4 Answers4

4

A return statement doesn't bubble up functions to the global scope, and if you look carefully, you can see that return val lives inside its own function.

In addition to that, that function isn't executed synchronously, so it will never have a chance to return before it's executed.

Therefore, you need to either pass in a callback or use a promises pattern. Googling these words will find you a wealth of information on both.

alex
  • 479,566
  • 201
  • 878
  • 984
0

Use promises to handle errors. It your code return 'error' will be called before callback in post method.

function test(){
   $.post('data.php', function(val){
       alert (val);
   }).fail(function(){ alert('error');});


}
maximus
  • 716
  • 7
  • 18
0

Try this one

function test(callback){
   $.post('data.php', function(val){
       if(typeof callback == 'function') callback(val);
   })
}

And call with

test(function(val){ console.log(val) });
brunettdan
  • 997
  • 9
  • 7
0

The function is returning 'error' before the post is finished because post is asynchronous. Try using callbacks. Something like this:

function test(callback) {
    $.post('data.php', function(val){
        callback(val);
    })
    .fail(function() {
        callback('error');
    });
}

function log(message) {
    console.log(message);
}

test(log);
Rush Frisby
  • 11,388
  • 19
  • 63
  • 83