Tarek Haddad Tarek Haddad - 5 months ago 37
jQuery Question

return true or false after ajax post in parent function?

I want to return true or false after making this ajax call:

function write_csv(data, path, file) {

$.ajax({
url: 'functions.php',
type: 'POST',
data: {
operation: 'SAVE_CSV',
save_path: path,
save_file: file,
save_string: data
},
success: function(result) {
console.log('write_file(' + path + file + '); -done');

return true; /* <-- */

}
});
}


Example use case of what I want:

function make_csv () {

/*
|
V
*/

if (write_csv(my_data, my_path, 'export.csv') == true) {
go_on();
}

function go_on() {
alert('YEAH!');
}

}


I know it's async, but maybe someone has another idea.
I won't do it with
if
's and stuff...

Answer

You can use Promises or callbacks to accomplish what you want.

function write_csv(data, path, file, callback) {

    $.ajax({
        url: 'functions.php',
        type: 'POST',
        data: {
            operation: 'SAVE_CSV',
            save_path: path,
            save_file: file,
            save_string: data
        },
        success: function(result) {
            console.log('write_file(' + path + file + '); -done');

            callback(true); /* <-- */

        }
    });
}

And:

function make_csv () {

    /* 
    |
    V
    */

    function go_on() {
        alert('YEAH!');
    }

    write_csv(my_data, my_path, 'export.csv', function(result) {
        if (result == true) {
            go_on();
        }
    });
}
Comments