Home > Software design >  Javascript reading old params from URL(GET method)
Javascript reading old params from URL(GET method)

Time:03-19

I am starting to learn JavaScript(coming from C , Java, Python) and I am facing the following problem. I want to make a simple login page, and pass the parameters like username and ppassword. With the POST method, everything works. Still, I wanted to try with the GET method where the parameters will be put in the URL, just to see the difference. The problem is that JS function always reads old values, so at the beginning after I click submit, it reads null for both username and password(because the starting link doesnt have any params) and later it always reads the old ones. It seems like URL doesnt update before JS script runs.

Any idea on how to solve this?

function validate() {
  var queryString = window.location.href;
  var url = new URL(queryString);
  var username = url.searchParams.get('username')
  var password = url.searchParams.get('password')
  console.log(username);
  console.log(password);
  if (username == "admin" && password == "admin") {
    alert("login successfully");
  } else {
    alert("login failed");
  }
}
<form  action="login.html" method="GET">
  <input type="text" name="username" placeholder="Enter your username" id="username">
  <br>
  <input type="password" name="password" placeholder="Enter your password" id="password">
  <br>
  <input type="submit" name="" value="Login" onclick="validate()">
</form>

CodePudding user response:

Separate the code into two files, one for home.html that contains the UI elements and form submit will pass the data to another file login.html. Also, removing the click event as it is already on submit type form will automatically submit the data to login.html given in submitting action.

Login.html

<script>
  var queryString = window.location.href;

  var url = new URL(queryString);

  var username = url.searchParams.get("username");
  var password = url.searchParams.get("password");

  console.log(username);
  console.log(password);

  if (username == "admin" && password == "admin") {
    alert("login successfully");
  } else {
    alert("login failed");
  }
</script>

home.html

<form  action="login.html" method="GET">
  <input type="text" name="username" placeholder="Enter your username" id="username">
  <br>
  <input type="password" name="password" placeholder="Enter your password" id="password">
  <br>
  <input type="submit" name="" value="Login">
</form>

enter image description here

enter image description here

  • Related