Reputation: 2117
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.
Upvotes: 0
Views: 2161
Reputation: 1757
AJAX is asynchronous. Therefore your call to alert(loadXMLDoc()) isn't actually returning anything.
xmlhttp.onreadystatechange=function()
{
...
}
This creates a new function and attaches it to the xmlHTTP object. When the state changes (the event is fired) this function is executed. It is NOT executed during the run of loadXMLDoc() but instead at some point in the future. This is done to maintain usability in your web application (things aren't waiting for something to complete).
The data that gets returned from your AJAX request has to be acted upon in this new function you've created. You should update the necessary pieces of your page w/ the returned information. It cannot return any data, well actually it can return all it wants but nothing will be done with that information.
You can also define a new function somewhere else and attach it to the onreadystatechange
event handler by doing:
function handler() { ... }
xhmlhttp.onreadystatechange = handler;
Upvotes: 1
Reputation: 3201
Because the return is in the scope of the xmlhttp.onreadystatechange
function and not your loadXML function. This is how asynchronous requests work, they run in the background while the code already continues. When the request is finished it calls a function, which is usually set on the onreadystatechange
.
So quick example; in FunctionA you start the XMLHTTP request, which on completion calls the onreadystatechange
function that calls FunctionB with the responseText.
If you want to have the code wait for a response, you need to use a synchronous request - however, doing so stalls the entire browser until the request finishes. So it's best to just adjust your code to what I wrote in the first paragraph.
Upvotes: 1