This is my code for an XMLHttpRequest to get data from a PHP page. When I alert the variable user_data inside an “if” it works. But below all of this code the variable doesn’t exist any more.
Thanks for the help!
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
user_data = xmlhttp.responseText;
alert (user_data); //THIS WORKS
}
}
xmlhttp.open("GET","http://myurl.com/index.php",true);
xmlhttp.send();
alert (user_data); //THIS DOESN'T WORK
It’s an asynchronous request. The non-working alert is executed before the request returns. The variable isn’t assigned until the request completes.