Search code examples
javascriptjqueryfunctionasynchronousreturn

How to use callback on $.post to get returned data (async function problem)


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
}

Solution

  • 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;
    }