This is because of the asynchronous nature of asynchronous requests ... hm I already told that someone a few hours ago ... I should make it my signature :-)
Code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response = xmlhttp.responseText;
}
}
document.write(response);
What happens here?
1. onreadystatechange is assigned a function, but this function is not called (yet).
2. That's why "response" is not set. document.write will write an empty string
3. In the meantime, the request will finish and populate "response" with the output of the script
4. By pushing the button the second time, you will start another request (whose onreadystatechange function is not called immediately) and output the previous "response" with document.write
Solution: You have to do everything you want to do after the onreadystatechange is fired within the onreadystatechange function:
Code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response = xmlhttp.responseText;
document.write(response);
}
}