Using $ .post in javascript function can't assign value to variable?
I am trying to use $ .post inside a function, get the results, and then return the function true or false based on the results of the $ .post callback. However, the callback seems to happen AFTER the parent function return event.
Here the current code always has the variable ret undefined, but if I warn it () in the $ .post callback, it returns the correct result;
function elementExists(key, type, path, appid, pid){
var ret;
$.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){
ret = data;
});
alert(ret);
return ret;
}
source to share
As you have found, the message is executed asynchronously. If you want it to be synchronous you need to use a method ajax
and set the parameter async
to false. It would be better, however, to acknowledge that the message is asynchronous and that your code generates such that the action that the callback takes is independent of the method that invokes the message. Obviously you really want to do something other than a warning, but not knowing that you are having a hard time advising on how to refactor this.
EDIT . I understand that your code is checking if something exists, but it checks for that for a specific purpose. If we knew what the purpose is, then it would be possible to recommend how to do it in the callback so that the method can be refactored.
source to share
function elementExists(key, type, path, appid, pid){
$.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){
alert(data);
});
}
function (data) is a callback (asynchronous), you cannot return values like this.
it is that the callback is not called until the page is called, but your "return ret" is executed immediately after the call to $ .post
If you want to set synchronous set async: false
See docs http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
source to share
The problem is your code is being executed asynchronously. This warning (ret) is actually called before ret = data, which happens when the Ajax request is complete.
You can either make your ajax calls synchronous (not recommended) using the async parameter , or reverse engineer your code.
source to share