Hey there, I'm new around here so I hope I got this right. Currently, I'm diving into the Ajax for Dummies book after enjoying the PHP one years ago. However, I've hit a roadblock with my first real Ajax program. It took me ages to locate the text file, and while troubleshooting the code, I stumbled upon an issue that has left me puzzled.
There's a section in the code where it checks if readyState == 4 AND status == 200, and if that condition is false, it displays an alert message saying "nope." Strangely enough, it always alerts "nope" even when executing the other part of the if statement. Why is that happening? Below is the only snippet of code I have at the moment - no additional files that could potentially interfere with the function. If I remove the "else" statement, everything works fine, but I'm concerned about potential issues down the line, which is why I'd like to understand why it's behaving this way. Thank you for your help!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<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, true);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
obj.innerHTML = XMLHttpRequestObject.responseText;
}
else
{
alert("nope");
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<H1>Fetching data with Ajax</H1>
<form>
<input type="button" value="submit" onclick="getData('http://localhost/AV/data.txt', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched data will go here.</p>
</div>
</body>
</html>