Bouffe Bouffe - 5 months ago 19
jQuery Question

Double ajax request response

I'm using ajax successives requests and I need do a callback when all the successives requests are done

function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
},
error:function (xhr, status, error) {
//Do something
}
});
},
error:function (xhr, status, error) {
//Do something
}
});
}

$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2){
//Need do something when both second ajax requests (example2.php) are finished
}


With this code, the done function is call before my calls to "exemple2.php" are succeeded.

How can I wait for that?

Thanks for answering!

Answer
function doAjaxRequest(data, id) {
    // Get payment Token
    return new Promise(function(resolve,reject){
        $.ajax({
        type: "POST",
        url: 'exemple1.php',
        data: data
        success: function(msg){
            $.ajax({
                type: "POST",
                url: 'exemple2.php',
                data: msg,
                success: function(msgr) {
                    document.getElementById(id).value=msgr;
                    resolve();
                },
                error:function (xhr, status, error) {
                    //Do something
                    reject();
                }
            });
        },
        error:function (xhr, status, error) {
            //Do something
            reject();
        }
    });
    });
}



Promise.all([
    doAjaxRequest(data, "input-1"),
    doAjaxRequest(otherData, "input-2")])
.then(function(values){
    //Need do something when both second ajax requests (example2.php) are finished
}
Comments