I\'m getting the following error
Uncaught TypeError: Cannot read property \'appendChild\' of null
myRequest.onreadystatechange @ script.js
There isn't an element on your page with the id "mainContent" when your callback is being executed.
In the line:
document.getElementById("mainContent").appendChild(p);
the section document.getElementById("mainContent")
is returning null
If this is happening to you in an AJAX post, you'll want to compare the values that you're sending and the values that the Controller is expecting.
In my case, I had changed a parameter in a serializable class from State to StateID, and then in an AJAX call didn't change the receiving field out 'data'
success: function (data) { MakeAddressForm.formData.StateID = data.State;
Note that the class was changed - it doesn't matter what I call it in the formData.
This created a null reference in the formData which I was trying to post back to the Controller once I'd done the update. Obviously, if someone changed the state (which was the purpose of the form) then they didn't get the error, so it made for a hard one to find.
This also through a 500 error. I'm posting this here in hopes it saves someone else the time I've wasted
Instead of using your script tag defining the source of your .js file in <head>
, place it at the bottom of your HTML code.
Use querySelector insted of getElementById();
var c = document.querySelector('#mainContent');
c.appendChild(document.createElement('div'));
add your script tag on the bottom of the body tag. so that script loads after html content then you won't get such error and add=
Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script>
but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.
window.onload = () => { //write your code here }
<script src="script.js"></script>
to the bottom of the html file so that it loads last.