response.Text is undefined when returning variable

Posted by George on Stack Overflow See other posts from Stack Overflow or by George
Published on 2010-05-26T16:25:54Z Indexed on 2010/05/26 16:31 UTC
Read the original article Hit count: 341

Filed under:

Not sure if the problem is related to Ajax or something silly about JavaScript that I'm overlooking in general, but I have the following script where fox.html is just plain text that reads, "The quick brown fox jumped over the lazy dog." :

function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.open("GET","fox.html",true);
xmlhttp.send();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    fox = xmlhttp.responseText;
    alert(fox);
    }
  }

}

onload = loadXMLDoc;

The above script alerts the contents of fox.html onload just fine. However if I change the script so that:

{
fox = xmlhttp.responseText;
alert(fox);
}

becomes:

{
fox = xmlhttp.responseText;
return fox;
}

and alert(loadXMLDoc()); onload I get 'undefined'.

I'm wondering why this is so.

© Stack Overflow or respective owner

Related posts about AJAX