1

Is there any way the callback function of XMLHttpRequest's onreadystatechange event can be external? What I mean is, instead of this:

var x = new XMLHttpRequest();
x.onreadystatechange  = function()
{
  if(x.readyState == 4 && x.status == 200)
  {
    document.getElementById("divName").value = x.responseText;
  }
} 

I'd like to do something like this:

function xResponse(xObj)
{
  if(xObj.readyState == 4 && xObj.status == 200)
  {
    return xObj.responseText;
  }
}

var x = new XMLHttpRequest();
document.getElementById("divName").value = xResponse(x);

However, it returns only undefined. Am I doing something wrong, or is this not possible?

Thank you.

Sofia

iSofia
  • 1,412
  • 2
  • 19
  • 36
  • Just do `x.onreadystatechange = xResponse(xObj);` – Rahil Wazir Feb 09 '14 at 12:49
  • 2
    Impossible - it's asynchronous so you can't `return`. See duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi Feb 09 '14 at 13:45
  • You can actually return a callback from `onreadystatechange`, but it would be thousands of milliseconds later and completely impractical. In short, Bergi is right - you can't do it. I cried too, but you'll get over it. – Adam McArthur Oct 08 '14 at 10:16

0 Answers0