I have two html files (index.html
and allUsers.html
) and a JavaScript index.js
The index.html has a button allUsersButton
.
My goal is that when the allUsersButton
is clicked, I should see the allUsers.html page, and be able to see the fetched data which should be injected into the div named allUsersDivId
.
So far, no data loads on the allUsers.html page and I get an error on the console “Uncaught TypeError: Cannot set properties of null (setting ‘onclick’)”.
Should both the index.html
and the allUsers.html
have the script linked in them? What’s the best way to put this together?
index.html
<body>
<form action="http://localhost:7050/hello" method="POST">
<label for="username">User name:</label>
<input type="text" id="username" name="username"><br><br>
<input type="submit" value="Submit">
</form>
<button type="button" id="allUsersButton">All Users</button>
<script src="index.js"></script>
</body>
allUsers.html
<body>
<div id = "allUsersDivId">
</div>
<script src="index.js"></script>
</body>
index.js
Here I have a function for fetching and inserting the data into the div allUsersDivId
which is in the allUsers.html
, and an onClick listening on the allUsersButton
which is in the index.html
.
document.getElementById("allUsersButton").onclick = function() {displayAllUsers()};
function displayAllUsers() {
window.location.href='allUsers.html'
fetch("http://localhost:7050/allusers")
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then(data => {
for(var i = 0; i < data.length; i++){
const userName = data[i].username
const userNameDiv = document.getElementById("allUsersDivId")
const heading = document.createElement("h1")
heading.innerHTML = userName
userNameDiv.appendChild(heading)
}
})
.catch((error) => console.error("FETCH ERROR:", error));
}
What’s the best way to link this all together?