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

Poshlik
  • 3
  • 2

1 Answers1

-1

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) {
          resolve(login.responseText);
        } else {
          reject("Status is not ok");
        }
      }
    };
  });
}

startbtn.forEach((button) => {
  button.addEventListener("click", async (e) => {
    try {
      const loginResult = await getLogin();
      if (loginResult == "true") {
      } else {
        alert("Вы не вошли в свой аккаунт!");
      }
    } catch (err) {
      console.error("Error during login");
      console.error(err);
    }
  });
});

You can also use a 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("Вы не вошли в свой аккаунт!");
    }
  });
});
nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • ```js const startbtn = document.querySelectorAll(".start-game"); startbtn.forEach((button) => { button.addEventListener("click", async (e) => { const loginResult = await getLogin(); if (loginResult == "true") { } else { alert("Вы не вошли в свой аккаунт!"); } }); // Uncaught (in promise) }); ``` gives the following error – Poshlik Jul 31 '23 at 08:08
  • Updated the answer – nick zoum Jul 31 '23 at 08:13