...

View Full Version : Why must I click submit twice?



brichcja
01-11-2011, 11:52 AM
Hi all.

This is my html code:



<body>
<script type="text/javascript" src="writexml.js"></script>
<script type="text/javascript" src="readxml.js"></script>

<script type="text/javascript">

function readxmldata(filename) {
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("POST","http://localhost/census/test.php",true);

poststring = "filename=" + filename;

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", poststring.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.setRequestHeader("charset", "utf-8");
xmlhttp.send(poststring);

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

document.write(response);
}

</script>

<input type="button" value="Submit" onclick="readxmldata('default.xml');"/>
</body>


and this is the test.php file that it calls:



<?php
echo "This is the test page";
?>


My question is simply: Why do I only get the response when I click the submit button twice? If I don't use a button but just try to call the "readxmldata" function using <body onload="readxmldata('default.xml');"> then I don't get any response at all.

Thanks,

Chris

devnull69
01-11-2011, 12:24 PM
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 :-)



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:


xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
response = xmlhttp.responseText;
document.write(response);
}
}

brichcja
01-11-2011, 01:45 PM
Thank you. That makes perfect sense.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum