Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
Ajax Request Answer is slower than code, ajax request after code is processed

I've got the ajax request is very slow so my stats array does not get updated at the second time i want to access it. It seems like the ajax request gets executed after all the code is processed. Is there a way how i can wait for the ajax request to be executed before all the rest of my code?

console.log(stats);
fetchREST(false, (url+selectedID+"/solve"), (parseInt(button.id)+1), function(data){
 if (data.success) {
  console.log("richtig");
  stats.right++;
 } else {
  console.log("falsch");
  stats.wrong++;
 }
});
console.log(stats);

function fetchREST(isGET, path, answer, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };

    let email = "*";
    let pw = "*";

    if(isGET) {
        // not needed
    } else {
        let solutionArray = '[' +  answer +  ']';
        console.log(solutionArray);
        httpRequest.open('POST', path, true);
        httpRequest.setRequestHeader("Content-Type", "application/json");
        httpRequest.setRequestHeader("Access-Control-Allow-Origin", "*"); 
        httpRequest.setRequestHeader("Access-Control-Allow-Headers", "*");
        httpRequest.setRequestHeader("Authorization", "Basic " + window.btoa(email + ":" + pw));
        httpRequest.send(solutionArray);
    }
}

EDIT I fixed it by changing

httpRequest.open('POST', path, true);

to

httpRequest.open('POST', path, false);

Now the async is set to false and the send methods waits until a response is received.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I fixed it by myself by changing

httpRequest.open('POST', path, true);

to

httpRequest.open('POST', path, false);

Now the async is set to false and the send methods waits until a response is received.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda