0

How can I return the output of an XMLHttpRequest as a variable? The output doesn't get passed outside the XMLHttpRequest!

What am I doing wrong? I thought it was a problem related to the asynchronous nature of the request and I tried changing the flag to FALSE and even implemented a delay-promise mechanism to make sure the output would get returned only when processed, but still it does not get passed outside as a parameter...

var testAVal = "SomeStringToBeProcessed";
var outputStr = MyFunction(testAVal); 

console.log("outputStr: ", outputStr); //ERROR! RETURNS undefined!
alert("outputStr: ", outputStr); //ERROR! RETURNS undefined!

function MyFunction(ValueToBeProcessed)
{
    var ReqQ = new XMLHttpRequest();
    ReqQ.onloadend = function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            return this.responseText;                   
        }
    };
    ReqQ.open("GET", "myphpfunction.php?pV=" + ValueToBeProcessed, true);
    ReqQ.send();
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
jeddi
  • 651
  • 1
  • 12
  • 21
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – VLAZ Apr 28 '23 at 12:19

1 Answers1

-3

I fixed your code,please use:

function MyFunction(ValueToBeProcessed){
    var ReqQ = new XMLHttpRequest()

    ReqQ.open("GET", "myphpfunction.php?pV=" + ValueToBeProcessed, true);
    ReqQ.send();
    setTimeout((function(){
        if (ReqQ.readyState == 4 && ReqQ.status == 200){
            return ReqQ.responseText;                   
        }
    }),2000)
}
SNQUphp
  • 16
  • 6
  • `return` inside a `setTimeout` callback won't produce the value *from the surrounding function*. Moreover, `setTimeout` is the completely wrong tool to use with HTTP requests, XMLHttpRequest *already* includes mechanism to respond to when it's done - it's registering event handlers. OP has done this with the [loadend event](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/loadend_event). The issue here isn't that the event doesn't fire and has to, for some reason, be manually and more crudely re-implemented with `setTimeout`. But that it's asynchronous code. – VLAZ Apr 28 '23 at 12:34