1
let request = new XMLHttpRequest();
let data;

request.open('POST', "https://example.page");

request.setRequestHeader(not important);
request.setRequestHeader(not important);
request.setRequestHeader(not important);

request.onreadystatechange = function () {
  if (this.readyState === 4) {
    data = this.responseText;
  }
};

const body = '{some values}';
request.send(body);

var test = data; <-- test ends up being undefined  

How can I use the value I get from the response text outside the function? I tried to do this with a callback function, but that didn't really work out.

I'm kinda new to javascript and I would really appreciate some help :)

ocrdu
  • 2,172
  • 6
  • 15
  • 22
DA123
  • 19
  • 1
  • this is async. you have to lean about promises – Mister Jojo Dec 22 '20 at 14:25
  • do you have a helpful website for me where I can give it a try? – DA123 Dec 22 '20 at 15:01
  • You are supposed to make a search... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise and https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr – Mister Jojo Dec 22 '20 at 16:11

0 Answers0