Forum Moderators: open
<html>
<head>
<meta name = "viewport" content = "initial-scale = 1.0, user-scalable = no" />
</head>
<body>
<script>
var browserCheck = (document.all) ? 1 : 0;
if( browserCheck > 0 ){
window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
xml = new XMLHttpRequest;
} else {
var xml = new XMLHttpRequest();
}
var data = "";
function paused() {
document.write(".");
}
function stateChange() {
document.write("Attempting to store data...<br>");
alert("Attempting to store data...<br>");
document.write("Loading...");
while(xml.readyState < 4) { setTimeout("paused()",500); }
document.write("<br>");
if (xml.readyState == 4){
document.write("XML Object State = "+xml.readyState+"<br>");
window.data = xml.responseText;
document.write("RESPONSE: "+xml.responseText+"<br>");
} else {
document.write("ERROR: readyState="+xml.readyState+"<br>");
document.write("RESPONSE: "+xml.responseText+"<br>");
}
}
document.write("Starting XMLRequestHeader<br>");
alert("Starting XMLRequestHeader<br>");
var url = "http://www.google.com";
xml.open("GET", url, true);
xml.send(null);
xml.onreadystatechange = stateChange();
document.write("DATA VAR = "+data+"<br>");
alert("DATA VAR = "+data+"<br>");
var check = data.indexOf("HTML");
if(check == -1) { ierror = true; }
if(ierror == true) {
document.write("ERROR: XML Request never recieved a response.<br>");
alert("ERROR: XML Request never recieved a response.<br>");
}
document.write("RESULT: "+xml.getAllResponseHeaders());
</script>
</body>
</html>
Works in IE. In Firefox and Safari, the response returned is empty, even with "OK" as status and readyState equal to 4.
Any idea what I'm missing?
Your AJAX request is asynchronous, so you can't know whether it will run before or after page load. If it runs AFTER page load, it will OVERWRITE your existing document (including any scripts or content already written to the page). Thus, your document containing all of your script might be replaced with a single character ("."). As already stated, don't use document.write.
If you need to write data to the page, use DOM methods like appendChild or modify the innerHTML of a page element. But you certainly DON'T want to use document.write.