0

i have a code that give problem on returning value from nested function.
check this code.

function test(){
  var flag=true;
  $.post('path/of/file.php',{data:data},function(r){
     if(r == 1){ flag=false; }
  });
      return flag;
}

this function test always return true. because it return value without waiting of call back function of $.post. if i return within the callback function it is not work. so, how can i overcome from this problem.
thanks...

AzeemHaider
  • 69
  • 1
  • 2
  • 8
  • Its quite unclear.. You want to return the value once you get value back from `post`? But you are always returning `true`? and that doesn't make sense whether or not you got value from `post`. Can you brief the scenario? – Guruprasad J Rao Sep 10 '15 at 05:00
  • 1
    i think you should return `return flag`; instead of `return true` – Mayank Pathak Sep 10 '15 at 05:02
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Michael Geary Sep 10 '15 at 05:26
  • You can't do what you are trying to do. The `$.post()` callback is called *asynchronously*. Returning a value from it, setting a flag, none of that will work. What you need to do instead is take whatever action you need *within* that callback function, or else call another function from inside there. See the link in the previous comment for more information. – Michael Geary Sep 10 '15 at 05:27

1 Answers1

0

Since .post runs async your method will always return true at the moment. But how about returning a deferred object instead? I realize that this is a different approach than the one you're asking for, and it might not be applicable for your scenario.

Something like this (from the top of my head):

function test(){
   var def = new $.Deferred();   
    $.ajax({
        url: 'test',
        success: function(data) {
            // Do some minor logic to determine if server response was success.
            console.log('success in callback');
            if(data == true){
              def.resolve(true);  
            }
            else{
              def.reject(); 
              // or possibly def.resolve(true) depending what you're looking for.
            }

        },
        error:function(){
          console.log('error in callback');
          def.reject();
        }
    });

  return def; 
}

function testMethod(){
  var defObject = test();
  defObject.done(function(result){
    console.log('done in deferred');
    // Do something when everything went well.

  }).fail(function(){
    console.log('error in deferred');
    // Do something when something went bad.
  });
}

$(document).ready(function(){
  testMethod();  
});

Deferred makes it easy to listen async callbacks. It's a common pattern when you want to do some logic efter a request is done, but you want to separate the logic from the request itself.

Some more examples here: http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt2-practical-use

A plunkr example: http://plnkr.co/edit/LsNjfx4alNzshOQb2XAW?p=preview

smoksnes
  • 10,509
  • 4
  • 49
  • 74
  • @smokesnes i check your code but it give error `uncaught typeError: cannot read property 'done' of undefined` – AzeemHaider Sep 10 '15 at 06:26
  • @AzeemHaider have you tried the Plnkr example? Open the console and it will write "Error", since the ajax request is failing. Is jQuery loaded? Can you write new $.Deferred() in the console? – smoksnes Sep 10 '15 at 06:30
  • @AzeemHaider I made a minor adjustment in the code and added more logging and remove some totally unrelated code. – smoksnes Sep 10 '15 at 06:44