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¶m2=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¶m2=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;};
}