javascriptxmlhttprequestresponsetext

How to get XMLHttpRequest responseText while using .bind in Javascript?


This is what I would LIKE to do:

response: string;
sendCreateInvoice(invoice, job){
  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      this.response = this.responseText;
    };
  };
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

so I THINK I need to use .bind(this) but when I do that I can't seem to access this.responseText anymore. I tried like this:

response: string;
sendCreateInvoice(invoice, job){
  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      this.response = this.responseText;
    };
  }.bind(this);
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

And I tried this.xmlhttp.responseText and xmlhttp.responseText but no luck. Where am I going wrong? How can I save the responseText to response?

==================

Working code:

response: string;
sendCreateInvoice(){
  let url = 'assets/php/myScript.php';
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = () => {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      this.response = xmlhttp..responseText;
    };
  };
  xmlhttp.open('POST', url, true);
  xmlhttp.send(invoice);
}

Solution

  • You can use xmlhttp to refer to the XMLHttpRequest object.

    And the calls to open() and send() need to be outside the callback function.

      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          this.response = xmlhttp.responseText;
        };
      }.bind(this);
    

    Also, instead of .bind(this), you can use an arrow function.

      xmlhttp.onreadystatechange = () => {
        if (this.readyState == 4 && this.status == 200) {
          this.response = xmlhttp.responseText;
        };
      };
      xmlhttp.open('POST', url, true);
      xmlhttp.send(invoice);
    

    Arrow functions treat this as a normal lexical variable.