0

I want to get the response text from php. I see it in the console as "responseText", but I can't get from my function codes variable.

When I run this code, console.log(query(path,"GET")), I see response in the screenshot. When I run this code console.log(query(path,"GET").responseText), I see only blank response.

PHP Code

<?php echo "Hi this is PHP Answer from Async XHR  request "; ?>

JavaScript Code

query=function(url,method){
    xhr=new XMLHttpRequest()
    xhr.url=url
    xhr.open(method,url,true)
    xhr.send()
    return xhr;
}

path="../../core/ajax/periyodikTarama.php"
console.log(query(path,"GET"))

Console Result

See the selected red text

enter image description here

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Computer
  • 3
  • 2
  • 1
    Probably because the request hasn't been resolved. Add an if statement `if (xhr.readyState === 4) { return xhr }` and then try to get the value – Vladimir Jovanović Aug 23 '19 at 13:13
  • Possible duplicate of [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) – misorude Aug 23 '19 at 13:13
  • XHR is async, so you will need to print out the response from a success function. – Mr. Polywhirl Aug 23 '19 at 13:15

1 Answers1

0

Not tested, but this is the proper way to handle the async response with a callback.

query = function(url, method, callbackFn) {
  xhr = new XMLHttpRequest();
  xhr.url = url;
  xhr.open(method, url, true);
  xhr.onload = () => {
    callbackFn(xhr.responseText); // Feed the response to the callback
  }
  xhr.send();
  return xhr;
}

path = "../../core/ajax/periyodikTarama.php"
query(path, "GET", (responseText) => {
  console.log(responseText); // Log the resonse text
})
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132