I am using the following code to show value return by the function test2.
The output showing is: Value of x is: undefined
Can anyone help me in explaining how can I return a value from function test2? Please note that the function test2 is XMLHTTPRequest
<script language="javascript">
function test1()
{
var x = test2();
alert('Value of x is: '+x);
}
function test2()
{
if(window.XMLHttpRequest)
{
abcd= new XMLHttpRequest();
}
else
{
abcd=new ActiveXObject("Microsoft.XMLHTTP");
}
abcd.onreadystatechange=function()
{
if (abcd.readyState==4 && abcd.status==200)
{
return abcd.responseText; // it is getting value 2 here
}
else if(abcd.readyState < 4)
{
return -1;
}
}
abcd.open("GET",sam.php,true);
abcd.send();
}
</script>
It sounds like you want the value from the XML HTTP request to be the return of
test2. This is simply not possible as this XML HTTP request executes asynchronously andtest2executes synchronously.The proper way to handle this is to pass a callback to
test2to execute at the completion of the request. The callback is provided the value which is returned from the XML HTTP request. For example