how to use an API on web, using Ajax and Javascript?

38 Views Asked by At

I want to implement a login by calling an API using Ajax and Javascript.

User enters username and password and by clicking a button "login()" would be called. If input is correct it should open the welcome page. I implemented it as below. But it does not work!

function login() {
  var url = "http://...";
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);

  xhr.setRequestHeader("Content-Type", "application/json");

  console.log("before function. ")    
  xhr.onreadystatechange = function () {
    console.log("before if. ")
    if (this.readyState == 4 && this.status == 200) {
      console.log("inside if. " + xhr.responseText);
      window.open(welcome);
    }
  };

  var obj = { UserName: username , Password: password }
  var data = JSON.stringify(obj);

  xhr.send(data);
  console.log("END ");
}

As suggested, I added several console log to debug it and I found out that it never run inside the if. There is no error on console and here's the output on console:

before function. 
END
before if.

(before was repeated 3 times)

I have already checked API by Postman. It works. If username and password are correct, it returns all information of user and the http status code is 201. If input is incorrect then it returns an error message and status code is 401.

0

There are 0 best solutions below