N
N
Nekio2021-07-02 17:30:12
AJAX
Nekio, 2021-07-02 17:30:12

How to make sequential ajax output on button click?

I want to display data from 2 different files sequentially (first from the 1st, then from the 2nd) by pressing a button.
In this case, it turns out that the 2nd is displayed faster, and the 1st is not displayed at all.

let result = document.getElementById('result');
    let button = document.getElementById('button');

    button.addEventListener('click', function() {
        let promise = fetch('ajax/first-p');
        let promise2 = fetch('ajax/second-p');

        promise.then(
            function(response){
            return response.text();     
            }).then(
                function(text){
                    result.innerHTML = text;
                }
            )
        
        promise2.then(
            function(response){
                    return response.text();
            }).then(
                function(text){
                    result.innerHTML = text;
                }
                
            )
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-07-02
@QuayS1de

Use async functions :

let result = document.querySelector('#result');
let button = document.querySelector('#button');

button.addEventListener('click', async function() {
    result.innerHTML = await (await fetch('ajax/first-p')).text();
    result.innerHTML = await (await fetch('ajax/second-p')).text();
});

Requests will be made sequentially, first the first, then the second. Just keep in mind that in such a scheme, the second request will then overwrite the output from the first request, but as I understand it, this is what you want. Plus, if you have fast internet, you might not even see the output from the first request, it makes sense to add a delay:
let result = document.querySelector('#result');
let button = document.querySelector('#button');

button.addEventListener('click', async function() {
    result.innerHTML = await (await fetch('ajax/first-p')).text();
    await wait(2000); // Ждём 2 секунды, только потом продолжаем
    result.innerHTML = await (await fetch('ajax/second-p')).text();
});

// Функция для выставления задержек:

function wait(ms) {
    return new Promise(function(success) {
        setTimeout(function() {
            success(true);
        }, ms);
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question