function getLogin(){
var login = new XMLHttpRequest();
let res; // variable
login.open('POST', 'assets/php/get_player.php', true);
login.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
login.send();
login.onreadystatechange = function() {
if (login.readyState == 4) {
if(login.status == 200) {
res = login.responseText; //Here the variable changes
}
}
}
return res
}
startbtn.forEach((button) => {
button.addEventListener('click', (e) => {
if (getLogin() == "true"){ // Here it gives undefined
}else{
alert("Вы не вошли в свой аккаунт!");
}
})
});
The ‘res’ variable changes, but ‘return’ returns undefined
Here is a code that does not work
Here is a code that does not work
>Solution :
You are dealing with async actions, the response from the server will always be received after JavaScript is done executing the getLogin function. You should resolve the result and await for it (notice how the functions are now async)
async function getLogin() {
return new Promise(function (resolve, reject) {
var login = new XMLHttpRequest();
login.open("POST", "assets/php/get_player.php", true);
login.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
login.send();
login.onreadystatechange = function () {
if (login.readyState == 4) {
if (login.status == 200) {
return resolve(login.responseText);
}
}
reject();
};
});
}
startbtn.forEach((button) => {
button.addEventListener("click", async (e) => {
const loginResult = await getLogin();
if (loginResult == "true") {
} else {
alert("Вы не вошли в свой аккаунт!");
}
});
});
You can also use an sync request (though that’s not recommended)
function getLogin() {
var login = new XMLHttpRequest();
let res;
login.open("POST", "assets/php/get_player.php", false); // false = not async
login.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
login.send();
if (login.readyState === 4) {
if (login.status === 200) {
res = login.responseText;
}
}
return res;
}
startbtn.forEach((button) => {
button.addEventListener("click", (e) => {
if (getLogin() === "true") {
} else {
alert("Вы не вошли в свой аккаунт!");
}
});
});