简体   繁体   中英

How to send API request from inside addEventListener in javascript?

I have an html file where I created some input fields from where I collect email and password from user. I then pass these values to a javascript file. I am using addEventListener() to detect clicking of the login button. Inside addEventListener() I call another function which basically sends API request to a backend server using XMLHttpRequest() . But it seems like the the request is not being sent to the server. Here is my code:

index.html

<html>
  <script src="index.js"></script>
  <label>Email :</label>
  <input type="text" name="email" id="email" />
  <br /><br />
  <label>Password :</label>
  <input type="password" name="password" id="password" />
  <br /><br />
  <button type="submit" id="login">Login</button>
</html>

index.js

document.addEventListener("DOMContentLoaded", function() {
  var signin_btn = document.getElementById("login");
  signin_btn.addEventListener("click", function() {
    validate();
  });
});

function validate() {
  console.log("validate running.");
  var username = document.getElementById("email").value;
  var password = document.getElementById("password").value;
  console.log("username: ", username);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      auth_token = JSON.parse(this.responseText)["token"];
      localStorage.setItem("auth_token", auth_token);
      console.log("auth from index.js: ", auth_token);
    }
    xhttp.open("POST", "http://127.0.0.1:5000/userauth/login", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify({ email: username, password: password }));
  };
}

When I run this code, only the console.log("username: ", username); part appears in the console. But the console.log("auth from index.js: ", auth_token); is not displayed. Seems like the request is not being executed at all. Also no errors are shown in backend as well. What is the issue?

You've put the code that sends the HTTP Request inside the onreadystatechange handler, so it is never fired. You want the open and send method calls to be outside the XHR handler, because right now your click event handler creates an XHR object, assigns it a handler...and does nothing else. You probably meant to do this:

function validate() {
  console.log("validate running.");
  var username = document.getElementById("email").value;
  var password = document.getElementById("password").value;
  console.log("username: ", username);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      auth_token = JSON.parse(this.responseText)["token"];
      localStorage.setItem("auth_token", auth_token);
      console.log("auth from index.js: ", auth_token);
    }
  };
  xhttp.open("POST", "http://127.0.0.1:5000/userauth/login", true);
  xhttp.setRequestHeader("Content-Type", "application/json");
  xhttp.send(JSON.stringify({ email: username, password: password }));
}

In general, I would recommend using a library like jQuery or the new Fetch API because doing manual XHRs like this is a pain. But other than this problem your code looks fine.

You wrote the request sending lines inside the function, which is a callback function. Change the validate() function according to the following code.


function validate() {
    console.log("validate running.");
    var username = document.getElementById("email").value;
    var password = document.getElementById("password").value;
    console.log("username: ", username);

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            auth_token = JSON.parse(this.responseText)["token"];
            localStorage.setItem("auth_token", auth_token);
            console.log("auth from index.js: ", auth_token);
        }
    };
    xhttp.open("POST", "http://127.0.0.1:5000/userauth/login", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify({ email: username, password: password }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM