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
$.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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With