Can anyone help me with this error?
Uncaught TypeError: Cannot read property 'appendChild' of null
myRequest.onreadystatechange @ script.js:20
Here's the code snippet where I'm facing the issue
// index.html
<html>
<head>
<title>Simple Page</title>
</head>
<body>
<div id="mainContent">
<h1>This is an AJAX Example</h1>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Let's take a look at my JavaScript file as well
// script.js
// 1. Create the request
var myRequest;
// Checking for browser compatibility
if(window.XMLHttpRequest) { // Firefox, Safari
myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // IE
myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. Setting up the event handler for our request
myRequest.onreadystatechange = function() {
console.log("We were called!");
console.log(myRequest.readyState);
if(myRequest.readyState === 4){
var p = document.createElement("p");
var t = document.createTextNode(myRequest.responseText);
p.appendChild(t);
document.getElementById("mainContent").appendChild(p);
}
};
// 3. Sending the request
myRequest.open("GET","simple.txt", true);
myRequest.send(null);
Also, here is the content of simple.txt
This is the contents of a simple text file.
I made sure to follow advice by placing the script tag at the bottom of the HTML from @Tejs here, but unfortunately, I'm still encountering this error.