Using $.post within a javascript function, cannot assign value to a variable?
Question
I'm trying to use $.post within a function, get the results, then return the function true or false based on the results of the $.post callback. However, the callback seems to occur, AFTER the return event of the parent function.
Here's the current code the ret variable is always undefined but if I alert() it within 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;
}
Solution
As you've discovered the post is done asynchronously. If you want it to be synchronous, you'll need to use the ajax
method and set the async
parameter to false. It would be better, however, to acknowledge that the post is asynchronous and build your code so that the action performed by the callback is independent of the method that invokes the post. Obviously, you really want to do something other than the alert, but without knowing what it's hard to advise you how to refactor this.
EDIT: I understand that your code is checking to see if something exists, but it is checking that for a purpose. If we knew what the purpose was, then it might be possible to recommend how to accomplish that in the callback so that the method could be refactored.
OTHER TIPS
function elementExists(key, type, path, appid, pid){
$.post('?do=elExists', {key: key, type: type, path: path, appid: appid, pid: pid},function(data){
alert(data);
});
}
the function(data) is a call back (Asynchronous) you can't return values like that.
it that callback is not called until the page is done being called, but your "return ret" is executing immediately after you call $.post
If you want to set it syncronous set async : false
See the docs http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
The problem is that your code executes asynchronously. That is alert(ret) is actually called before ret = data, which happens when the Ajax request is completed.
You can either make your ajax calls synchronous (not recommended) by using the async option, or redesign your code.