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

265
Views
How to get xhr data in javascript

I'm a newbie at javascript and I made this script which runs on page load:

function checkItem(itemToCheck) {
  console.log(`Checking if ${itemToCheck} is checked`)
  var url = `https://list.s40.repl.co/api/get-status/${itemToCheck}`;

  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);

  xhr.setRequestHeader("Accept", "application/json");

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
    }};

  xhr.send();
  if (status === 200) {
    console.log("The request worked")
    if (response == `True`) {
      console.log(`${itemToCheck} is true`)
      var checkbox = document.getElementById(`${itemToToggle}-checkbox`)
      //Control the checkbox
    }
  }
}

It never outputs the "The request worked" text, and it seems to be because the xhr.status and xhr.responseText are blank outside of that function they're in. I know nothing about javascript and I don't know how to fix this. All I want to do is be able to request data and then do something with it if it equals true. Please help

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I get xhr.status == 0, which means the request failed. When I run the request through postman, I get an SSL error (certificate has expired). That is probably why the request fails.

Running it with fetch is not a problem though. So fetch seems to skip the SSL error. There doesn't seem to be a way to make XMLHttpRequest ignore this SSL error, though.

fetch(`https://list.s40.repl.co/api/get-status/2`)
  .then(res => res.text())
  .then(console.log)

I advise you to check if you can just use fetch for the task. Only very old browsers don't support it: https://caniuse.com/fetch

It is higher level and async by nature. You should generally prefer async code over synchronous when writing for the browser, as synchronous code blocks execution quickly and slows down your browser application or makes it even freeze.

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!