0

I am using this code to get the contents of data.dat. Here are the files:

main.js

function getData() {
  var result;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      result = this.responseText.split(",");
    }
  };
  xhttp.open("POST","data.dat",true);
  xhttp.send();
  return result;
}

data.dat

A,B,C

However, getData() returns an empty string. When I log this.responseText this way:

if (this.readyState == 4 && this.status == 200) {
  console.log(this.responseText);
  result = this.responseText.split(",");
}

I get ["A","B","C"]. What am I doing wrong?

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36

1 Answers1

1

Since AJAX stands for Asynchronous JavaScript And XML, you're using an asynchronous call in order to get your desired output. The issue is that return result statement is returned before your AJAX call is finished and that's why you're receiving empty result.

You should use a callback function.

function getData(callback) {
  var result;
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      result = this.responseText.split(",");
      callback(result);
    }
  };
  xhttp.open("POST","data.dat",true);
  xhttp.send();
}

getData(function(result){
  console.log(result);
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128