0

I would like to assign an XMLHttpRequest response to a variable using a return statement, but I am getting an undefined result. I am guessing that the assignment is trying to execute before the response is ready.

var x = req('param=val&param2=val2'); // x results in 'undefined'
function req(request) {
  var xhr=new XMLHttpRequest();
  xhr.open("post","parser.php");
  xhr.responseType="text";
  xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
  xhr.send(request);
  xhr.onreadystatechange=function(){
    if(this.readyState==4&&this.status==200) return this.response;};
}

I was previously using setInterval() for every assignment, but it's more verbose than I'd like:

req('param=val&param2=val2');
var wait=setInterval(function(){if(php!=null){
   x = php;
   clearInterval(wait);}
},10);
function req(request) {
  var xhr=new XMLHttpRequest();
  xhr.open("post","parser.php");
  xhr.responseType="text";
  xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
  xhr.send(request);
  xhr.onreadystatechange=function(){
    if(this.readyState==4&&this.status==200) php = this.response;};
}
icecub
  • 8,615
  • 6
  • 41
  • 70
Jonah M
  • 300
  • 2
  • 13
  • Please do not tag PHP when your question is a purely Javascript issue. Just because you are using PHP server side, does not mean your question has anything to do with it. As for your question: Keep in mind that `return` means it's returning something to the function caller. You are basicly trying to return data towards the `xhr.onreadystatechange` here. – icecub Jul 10 '19 at 02:32
  • noted! thanks for the feedback – Jonah M Jul 10 '19 at 03:09

0 Answers0