Reputation: 151
I'm trying to create an html table with pagination. I'm requesting JSON data via $.get call using JQuery which is an async call. The solution I currently have duplicates the HTML code whenever a new page is selected. I know this is an asynchronocity but I'm not exactly sure what the best method to overcome this would be.
<script type="text/javascript">
function generateTable(currentPage) {
this.URL = "https://jsonplaceholder.typicode.com/posts";
$.getJSON(URL, function(data) {
const pages = Math.ceil(data.length / 10);
for(let i = currentPage*10; i<(currentPage*10)+10; i++ ) {
let post = data[i];
let tblRow = "<tr>" + "<td>" + post.userId + "</td>" + "<td>" + post.id + "</td>" + "<td>" + post.title + "</td>" + "<td>" + post.body + "</td>" + "</tr>"
$(tblRow).appendTo("#jsonData tbody");
}
for (let i = 1; i <= pages; i++) {
let pagingHtml = "<a href=# onclick=generateTable("+(i-1)+")>"+" "+i+" "+"</a>"
$(pagingHtml).appendTo("#paging");
}
})
}
generateTable(0);
</script>
Upvotes: 0
Views: 3930
Reputation: 350107
Before populating the HTML, clear out the current rows from the page:
$("#jsonData tbody,#paging").empty();
This assumes that those two parent elements only have dynamic content. If not, you should reference container elements that only have dynamic content (so no headers, footers, ...etc).
Upvotes: 2