0

I'd like to get true or false from $.post by calling abc(). I found this answer, but I don't get it to work.

Can someone give me a short example with my code?

function abc() {
    form = $('form');
    formData = form.serialize();

    $.post('file.php', formData, function(result) {
        form.each(function() {
            if (result === this.id) {
                return true;
                error = true;
            }
        });

        if (error === false) { // no error
            return true;
        }
    });
}

if (abc()) {
    // true // <- doesn't work, because $.post is an async function
}
xif80599
  • 49
  • 1
  • 7

2 Answers2

0

Have in mind that the response of the call to $.post is only available when the promise fulfills.

So, in order for the response to be available, you have to wait for the promise (as you do in abc in order to know what to return).

Having that in mind, you have to return the promise in abc in order to wait for its resolution:

function abc() {
    form = $('form');
    formData = form.serialize();

    // Note here we return the promise
    return $.post('file.php', formData, function(result) {
        if (result === 'abc') {
             return true;
        } else {
             return false;
        }
    });
}

// Now we wait for the promise to be resolved
abc().then(function(result) {
    if (result) {
        // Do your thing here!
    }
});
mgarcia
  • 5,669
  • 3
  • 16
  • 35
  • The problem now is, that result is always "true" because it shows me the returned data from php and not just true or false :/. – xif80599 Feb 01 '20 at 15:30
0

You can achieve it by returning promise value, Then check it by using done method.

function abc() {
   form = $('form');
   formData = form.serialize();

   return $.post('file.php', formData);
}

abc().done(function(result){
    if(result === 'abc')
    // do something.
});

You can also use Callback function like this

function abc(mycalback) {
    form = $('form');
    formData = form.serialize();

    $.post('file.php', formData, mycalback);
}

function mycalback(response) {
    var result = false;
    form.each(function() {
            if (response=== this.id) {
                return true;
                result = true;
            }
        });
    return result;
}
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56