2

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;

}

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I have moved to use the $.ajax function instead, and it works a treat.
1
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

2 Comments

I don't think post supports setting the async option.
All the Ajax calls do, call $.ajaxSetup first
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.