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
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.