AJAX request with FOR

0

My real question is: do you understand why your loop executes in the first ajax request, only to then loop in the second ajax request?

Today I have this result:

HTMLandJScode

<html><head></head><body></body><scriptsrc="../jquery-3.3.1.min.js"></script>
</html>
<script>
$(document).ready(function(){

});

function call(){
    for(i = 0; i <= 5; i++){
        $.ajax({
            url: 'json.json',
            type: 'get',   
            success: function(data){
            call_1(data['data'].one);
            $.ajax({
                url:'json.json',
                type: 'get',
                success: function(data){
                    call_2(data['data'].two);
                }
            });
            }
        });
    }
}

function call_1(res){
    $('body').append(res);
}

function call_2(res){
    $('body').append(res+'<hr>');
}

</script>

My json.json file:

{
    "data": {
        "one": "Hello",
        "two": " World"
    }
}

I solved sending along with ajax options o:

async: false,

Looking like this:

function call(){
    for(i = 0; i <= 5; i++){
        $.ajax({
            async: false,
            url: 'json.json',
            type: 'get',   
            success: function(data){
            call_1(data['data'].one);
            $.ajax({
                async: false,
                url:'json.json',
                type: 'get',
                success: function(data){
                    call_2(data['data'].two);
                }
            });
            }
        });
    }
}
    
asked by anonymous 05.12.2018 / 18:21

1 answer

0

You can do a recursive function instead of a for

function call(index) {
    $.ajax({
        url: 'json.json',
        type: 'get',
        success: function (data) {
            call_1(data['data'].one);
            $.ajax({
                url: 'json.json',
                type: 'get',
                success: function (data) {
                    call_2(data['data'].two);
                }
            });
        }
    });
    setTimeout(function () {
        if (index < 5) {
            index++;
            call(index);
        }
    }, 50);
}
Reminding where to call the call function start with index 0     
05.12.2018 / 19:32