Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cant I return data from $.post (jquery)

Tags:

jquery

post

I must be making a silly mistake but I cannot return the data I get from a $.post function and store it in a variable, not only that, I cannot return ANYTHING from within that function. Example:

function test(){

$.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      return(data)
    });

}

var foo = test()
alert(foo)

it say's that foo is undefined. But to take it a step further, even when I do this:

function test(){

    $.post("demo_test_post.asp",
        {
          name:"Donald Duck",
          city:"Duckburg"
        },
        function(data,status){

          var bar = "bar"
          return(bar)
        });

    }

    var foo = test()
    alert(foo)

it STILL says foo is undefined... I must be doing something wrong or misunderstanding something. Can someone please help.

Thanks

like image 533
Sam Creamer Avatar asked Jun 07 '13 15:06

Sam Creamer


2 Answers

$.post is a asynchronous function. The control from function will immediately return after it run post but the response from post may be received later.

So what you can do is instead of return, use a call back function and define callback function outside.

say,

function test(){

  $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      my_function(data)
    });

}

function my_function(data){
  // you can operate on data here
}
like image 139
Nagarjun Avatar answered Oct 10 '22 01:10

Nagarjun


You don't return anything from post(). What you have inside function(data, status) {} is actually a callback and doesn't return a result to the post() method like you think.

Have a read of the this article for more information

like image 32
CodingIntrigue Avatar answered Oct 09 '22 23:10

CodingIntrigue