How to call a function when all ajax calls in a function are complete?

I have a search problem when all ajax are complete. Here is my function.

function getValuesForTablePropertySelected(questionList, itemsArray) {
    for (var i = 0; i < itemsArray.length; i++) {
        switch (itemsArray[i]) {
        case "Tags":
                loadTag(questionList);
                break;
        case "Date Created":
                displayTablePropertySelected(itemsArray);
                break;
        case "Date Last Used":
                loadDLU(questionList);
                break;
        case "Number of Launched Surveys Used In":
                loadNLSU(questionList);
                break;
        case "Number of Reponses":
                loadNR(questionList);
                break;
        case "Type 1 Associations":
                loadT1A(questionList);
                break;
        case "Type 3 Associations":
                loadT3A(questionList);
                break;
        case "Sites Linked To":
                loadSLT(questionList);
                break;
        case "Last Modified By":
                displayTablePropertySelected(itemsArray)
                break;
        default:
                break;
        }
    }
    showResult();
}

Each function in "CASE" contains an ajax call. I need to use asynchronous calls .

I want to run the showResult () function after completing AJAX in all functions. Different AJAX take different time frames.

Please help me find a solution to this situation.

0
source share
2 answers

You can do this easily with jQuery .ajaxComplete():

// create a counter (global)
var ajax_calls_counter = 0;

// in your current code, in each ajax call success, add 1 to the counter

// manage ajax succeeded events
$(document).ajaxComplete(function(){
    if( ajax_calls_counter == itemsArray.length ){
        showResult();
    }
});

Example ( jsFiddle ):

$(function(){

    $(this).ajaxComplete(function(){
        var $body = $('body');
        $body.append('ajax number '+ counter +' call complete!<br />');
        if( counter == array.length ) $body.append('<strong>all</strong> ajax calls completed');
    });

    var array = [1, 2, 3, 4, 5];
    var counter = 0;

    for( var i = 0; i < array.length; i++ ){
        $.ajax({
            url: location.href,
            success: function(){
                counter++;
            }
        });
    }
});
+3
source

AJAX. . AJAX, , /, AJAX.

,

0

Source: https://habr.com/ru/post/1628870/


All Articles