Jquery – Using $.post within a javascript function, cannot assign value to a variable

globaljquerypostvariables

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;

}

Best 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.