Hi everyone
I've been looking at some code from the 'Ajax for Dummies' book (page 67). I'm running the code samples on an XAMPP installation with both files in the C:\xampp\htdocs folder which (appears) to have been set up as 'localhost'. However, there are 3 odd things about this code.
1 It will not work as stated unless I change the line
XMLHttpRequestObject.status == 200
to
XMLHttpRequestObject.status == 0
2 If instead of the line
onclick = "javascript: getData('data.txt',
'targetDiv')" (which works) I put - as suggested in the book -
onclick = "javascript: getData('http://localhost/data.txt',
'targetDiv')" - it does not work. It's as if it doesn't recognise local host.
3 If I move the html file and the data.txt file together to any folder outside of the local host altogether, having implemented the above changes, it still works! I thought AJAX was only supposed to work out of a server environment?
Can anyone enlighten me as to what may be going on? Has anyone been able to make this work in a localhost setup?
<html>
<head>
<title>Ajax at work</title>
<script language = "javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200 ) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<H1>Fetching data with Ajax</H1>
<form>
<input type = "button" value = "Display Message"
onclick = "javascript: getData('data.txt',
'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched data will go here.</p>
</div>
</body>
</html>