-1

I want 'this.responseText' which is an array to be returned out of this function and set as 'teacherIDList' but I have no clue how. Any help?

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var teacherIDList = eval("(" + this.responseText+ ")");
    }
}

xmlhttp.open("GET", "getTeacherID.php?q=" + subjectID, true);
xmlhttp.send();     
Dilly
  • 39
  • 4

1 Answers1

0

You have several methods of doing so.

Define the variable outside of the function:

var teacherIDList;

function doXHR() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      teacherIDList = eval("(" + this.responseText+ ")");
    }
  }

However, with this method, you don't know when the XHR will complete and teacherIDList is populated. This might be ok depending on how you're using the variable, but a much better way is to use a promise:

Use a promise:

function doXHRPromise() {
  return new Promise(function(resolve, reject) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        resolve(this.responseText);
      }
    }
  }
  ...
}

doXHRPromise.then(function(responseText) {
  var teacherIDList = eval("(" + this.responseText+ ")");
  // do whatever else you need to do here
});

This way you can ensure that teacherIDList is populated before acting on it.

P.S. Do NOT use eval(), you're opening yourself up to cross-site scripting attacks.

See this link for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Daniel T.
  • 37,212
  • 36
  • 139
  • 206