Search code examples
javascriptasynchronoustypescriptxmlhttprequest

Method in class not being called after XMLHttpRequest is done


I have the following method to log into my API:

login()
{
    var formData = new FormData();

    formData.append("admin[email]", "user");
    formData.append("admin[password]", "pass");

    var request = new XMLHttpRequest();
    request.open("POST", "my_link");

    request.onreadystatechange = (function() {
      if (request.readyState === XMLHttpRequest.DONE && request.status === 201)
      {
        return function() { this.loadMembers(); }
      }
    });

    request.send(formData);
  }

Then I have my method that I'm trying to call AFTER my post async request is completely done:

loadMembers()
{
    ....
}

Now for some reason, this.loadMembers() is never being called. If I put a testing console.log() right above it (not within the return callback) it calls just fine - so I know that the requestState and request status is correct.

Is there a better way to do this? Or what am I doing wrong?

Thanks


Solution

  • It is because you are returning a function instead of just calling loadMembers.

    So instead of:

    request.onreadystatechange = (function() {
      if (request.readyState === XMLHttpRequest.DONE && request.status === 201)
      {
        return function() { this.loadMembers(); }
      }
    });
    

    You likely want:

    var that = this;
    request.onreadystatechange = (function() {
      if (request.readyState === XMLHttpRequest.DONE && request.status === 201)
      {
        that.loadMembers();
      }
    });