Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!