I have a function in my JS file that brings back data from a PostgreSQL table. I want to display the results in a table in my HTML file but at the moment I am getting an undefined response.
JS function:
function ReadAllResult(json, status, req)
{
let html ="";
for (let s in json)
{
let student =json[s];
html += `Name: ${student.Name} `;
html += `Age: ${student.Age} Course: ${student.Course}<br/>`;
}
$("#all-students tbody").append(`<tr><td>${html.Name}</td><td>${html.Age}</td><td>${html.Course}</td></tr>`);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title>See All Products Page</title>
<meta charset="utf-8" />
</head>
<body>
<form action="" method="POST">
<input id="read-button" type="button" value="See all Products" />
</form>
<!-- <div id ="all-students"> </div> -->
<table id="all-students">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Course</th>
</tr>
</thead>
<tbody>
<tr>
<td>Loading..</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="js/readstudentspage.js"></script>
</body>
</html>`
2
Answers
Assuming you get the JSON from a file using $.getJSON or other AJAX, the data is an object when it reaches the function
Also assuming the JSON looks like this
[{"Name": "Joe", "Age" : 18, "Course": "JS101"}, {"Name": "Brad", "Age" : 17, "Course": "Algebra"}]
we can have a process like this
Your code had some issues :
I have Used your logic and fixed it.