I wanted to make a TO-DO list app for an assignment using https://jsonplaceholder.typicode.com/todos. The code snippet is shown below.
function generateList() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var output = "";
for (let i = 0; i < response.length; i++) {
// console.log(response[i].title);
if (response[i].completed == true) {
output += `<tr id='row${response[i].id}'>`;
output += `<td><input type="checkbox" id="task${response[i].id}" checked disabled></td>`;
output += `<td>${response[i].title}</td>`;
} else {
output += `<tr id='row${response[i].id}'>`;
output += `<td><input type="checkbox" id="task${response[i].id}"></td>`;
output += `<td>${response[i].title}</td>`;
}
output += "</tr>";
}
// document.querySelector("tbody").innerHTML = output;
return output;
}
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos", true);
xhttp.send();
}
let temp = generateList();
document.querySelector("tbody").innerHTML = temp;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Success</h1>
<table>
<tbody>
</tbody>
</table>
<script src="./json.js"></script>
</body>
</html>
The problem I am facing is that, the table is not displaying. Instead it is showing undefined. When I used the innerHTML method inside the function instead of return statement (I have commented that statement above the return statement), it worked perfectly as I wanted. Can anyone tell me, why am I facing this error?