How to render a table using javascript with foreach loop - javascript

I have a table whose tr needs to be repeat by rendering the value inside td. The values of td comes from get api call using foreach loop. I have already tried to render but my tbody is not coming inside the table. I want it to create using only javascript, no jquery.Here is the code below
var container = document.getElementById("container");
var url = "http://dummy.restapiexample.com/api/v1/employees";
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
container.innerHTML = '<div class="container"><h2>Basic Table</h2><p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p><table class="table"><thead><tr><th>ID</th><th>Firstname</th></tr></thead>'
data.data.forEach(function(count) {
console.log(count);
container.innerHTML += '<tbody><tr><td>' + count.id + '</td><td>' + count.employee_name + '</td></tr></tbody>';
})
}).catch(function() {
console.log("Booo");
});
container.innerHTML = '</table></div>'
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div id="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p>
</div>

Make a table and tbody since start and insert rows with forEach
var container = document.getElementById("container");
var url = "http://dummy.restapiexample.com/api/v1/employees";
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
data.data.forEach(function(count) {
console.log(count);
let tableBody = document.getElementById("tableBody");
tableBody.innerHTML += '<tr><td>' + count.id + '</td><td>' + count.employee_name + '</td></tr>';
})
}).catch(function() {
console.log("Booo");
});
container.innerHTML = '</table></div>'
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div id="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and horizontal dividers) to a table:</p>
<table class="table">
<thead>
<tr>
<th>ID</th><th>Firstname</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</div>

const root = document.getElementById("root");
const data = [{id:1, name:'kashif'}];
data.forEach((e) => {
root.innerHTML += `<td> ${e.id} </td><td> ${e.name} </td>`;
});
<table>
<thead>
<td>id</td><td>name</td>
</thead>
<tbody id="root"></tbody>
</table>

Related

How to insert data from Google Sheets into HTML Template (dynamic fields)

I am a newbie and rather a passionate starting to learn programming, than experienced guy.
I have done my research, yet unsuccessful, on how to get data from a Google Sheet and insert cell values into pre-made HTML template.
Task at hand is to generate employees email signatures prepared in HTML. Doing it manually was too time consuming and prone to mistakes.
Any change or update is really painful with this method.
I have found this tutorial and implemented it successfully
https://www.bpwebs.com/pull-data-from-google-sheets-to-html-table
After that I tried to replicate what was working in new project, but no results.
Ideally, expected result would be to run the app and be provided with as many ready HTML files as there are rows in the source Sheet file. There is also one condition, where one of the fields is to be displayed only for some employees (if blank, then insert nothing).
Please note I am very new to javascript, but eager to learn.
EDIT:
I have been asked to share what I have prepared by now. Cannot paste it in comments due to characters limit.
This is the Apps Script that shows simplified version of HTML that I am trying to manipulate. I was able to prepare a JS that changes name and surname as well as controls a portion of scr of img tag.
https://script.google.com/macros/s/AKfycbx6fapewLMLxgzrRKAY2bybR6HUngoA0sd-CaJHvXxF7TsbByqRWV_4cNpwzPAJJTJvpw/exec
(it should require Google account sing in. Unfortunately, option to share publicly disappeared)
I am also sharing a HTML with script put inside head section (in the Apps Script I have separate 'javascript' file that I am calling in HTML template file)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#300;600;800;900&display=swap" rel="stylesheet">
<script>
window.onload = function() {
//I need the var name to be pulling data from the Google Sheets
var name = 'blank-profile-picture-973460_1280';
var imgsrc = name;
document.getElementById('imgSource').src = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/' + imgsrc + '.png';
var emName = 'Joe';
var emSurname = 'Doe';
document.getElementById('Name').innerHTML = emName
document.getElementById('Surname').innerHTML = emSurname
};
</script>
</head>
<body>
<table cellspacing="0" cellpadding="0" border="0" style="vertical-align:-webkit-baseline-middle;font-family:'Poppins', sans-serif;">
<tbody>
<td>
<td valign="middle" style="padding-left: 0px; padding-top: 0px; padding-bottom: 0px; padding-right: 20px;">
<span style="margin:0px;font-family:'Poppins', sans-serif;font-size:20px;font-weight:800; padding-top:5px;color:black" id="Name" ></span> <span style="margin:0px;font-family:'Poppins', sans-serif;font-size:20px;font-weight:800; padding-top:5px;color:#3d85c6" id="Surname"></span><br><img width="158" height="158" min-height="158" min-width="158" max-height="158" max-width="158" src="" id="imgSource">
</td>
</td>
</tbody>
</body>
</html>
In the article linked above, they are pulling whole table using array. Now I need to either map a whole columns (Name, Surname, img src) or specific cells to pull these values.
Best Regards,
Mac
Here is an example of how to create a table using both templated HTML and google.script.run
I create a simple spreadsheet as shown.
Next in Code.gs I create my scripts
function showTest() {
var html = HtmlService.createTemplateFromFile("HTML_Test");
SpreadsheetApp.getUi().showModalDialog(html.evaluate(),"Test");
}
function getData() {
try {
let spread = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spread.getSheetByName("Sheet2");
let values = sheet.getDataRange().getDisplayValues();
values.shift(); // remove header
return values;
}
catch(err) {
Logger.log(err);
}
}
For templated HTML I create my page HTML_Test.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table, th, td {
border:1px solid black;
}
</style>
</head>
<body>
<? var data = getData(); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<td><?= data[i][0] ?></td>
<td><?= data[i][1] ?></td>
</tr>
<? } ?>
</table>
</body>
</html>
Or using an Immediately Invoked Function HTML_Test
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table, th, td {
border:1px solid black;
}
</style>
</head>
<body>
<table id="table">
</table>
<script>
( function () {
try {
google.script.run.withSuccessHandler(
function (data) {
let table = document.getElementById("table");
for( let i=0; i<data.length; i++ ) {
let row = document.createElement("TR");
let cell = document.createElement("TD");
let text = document.createTextNode(data[i][0]);
cell.appendChild(text);
row.appendChild(cell);
cell = document.createElement("TD");
text = document.createTextNode(data[i][1]);
cell.appendChild(text);
row.appendChild(cell);
table.appendChild(row);
}
}
).getData();
}
catch(err) {
alert(err);
}
}
)();
</script>
</body>
</html>
And the results are
Reference
Templated HTML
google.script.run()

Building a simple website that outputs results from a CSV using user’s input

https://levelup.gitconnected.com/building-a-simple-website-that-outputs-results-from-a-csv-using-users-input-bfcb782ced45
Hi, I am new to JavaScript. I came across this above tutorial and am trying to get it working so that i can then modify it for a little project i am working on. I hope to learn from it as I progress my project. I cant learn at the moment as I dont know whether its right or wrong.
I have created the html and JS file and have tested that they are linked. (I wrote an alert in the JS file that got triggered in the html file. I also added a quick script that gave a text alert when the button was pushed in html file).
I believe I have the same CSV file that the author was using but I cant be 100%. I can only assume I have introduced some error in the JS file and therefore its not reading the CSV file correctly. I have been at this for days and come up with nothing. Any help greatly appreciated.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class=”container”>
<div class=”row”>
<div class=”col-md-12">
<h1 class=>Find Movies!</h1>
<h2 class=>Enter the name of an actor/actress to see his/her best movies!</h2>
<form id=”form”>
<input class=”form-control” id=”user-input” placeholder=”Enter actor/actress…”>
<button id=”button” class=”btn btn-secondary”>Find Movies!</button>
</form>
<table class="table" cellpadding="10">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Movie</th>
<th scope="col">Rating</th>
<th scope="col">Year</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
</div>
</div>
</div>
<script src="app.js" charset="utf-8"> </script>
</body>
</html>
JavaScript (app.js)
d3.csv("movies.csv").then(function (data) {
var movies = data;
var button = d3.select("#button");
var form = d3.select("#form");
button.on("click", runEnter);
form.on("submit", runEnter);
function runEnter() {
d3.select("tbody").html("")
d3.event.preventDefault();
var inputValue = d3.select("#user-input").property("value");
var filteredMovies =
movies.filter(movies => movies.actors.includes(inputValue));
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
var output = _.sortBy(filteredMovies, 'avg_vote').reverse()
for (var i = 0; i < filteredMovies.length; i++) {
d3.select("tbody").insert(“tr").html(
"<td>" + [i+1] + "</td>" +
"<td>" + (output[i]['original_title'])+”</a>”+“</td>” +
"<td>" + (output[i]['avg_vote'])+"</td>" +
"<td>" + (output[i]['year'])+"</td>" +
"<td>" + (output[i]['description'])+"</td" ) }
};
});
Extract from movies.csv

Display javascript array in div

I am trying to make a basic to do application.
Here is what I have done so far;
When the user clicks a button a prompt appears asking the user to enter a task.
The task will then be stored in an array
I have displayed the array in the console. However, I am having trouble displaying the array on the web page:
var toDoItems = [];
var parsed = "";
document.getElementById("addItem").onclick = function() {
var userInput = prompt("Enter your Todo: ")
toDoItems.push = userInput;
console.log(toDoItems);
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
</html>
The first thing is you need to use Array.push() and not Array.push = someVal. Then you can loop over to the values and create a list of elements in the HTML:
var toDoItems = [];
var parsed = "";
document.getElementById("addItem").onclick = function() {
var nHTML = '';
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
toDoItems.forEach(function(item) {
nHTML += '<li>' + item + '</li>';
});
document.getElementById("item-list").innerHTML = '<ul>' + nHTML + '</ul>'
}
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
You can use map() to map over the toDoItems and convert each items to html code and then use join() to combine the array into one string of HTML code.
Like this:
const HTML = toDoItems.map( item => `<li>${item}</li> ` ).join('');
document.getElementById("item-list").innerHTML = '<ul>' + HTML + '</ul>'
Edit: Fixed typo (should be join, not joint)
Loop over toDoItems, create a <p> tag and append it to #item-list:
toDoItems.forEach((item) => {
let p = document.createElement('p');
p.innerText = item;
document.querySelector('#item-list').appendChild(p);
});
You can use innerHTML for this
document.getElementById("item-list").innerHTML += "<p>" +userInput+"</p>";
demo : plunker
Check below I think this may help you
I removed style from your code for my convenience
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>To Do List</title>
<script>
function myFunction(){
var toDoItems = [];
var parsed ="";
var userInput = prompt("Enter your Todo: ")
toDoItems.push = userInput;
document.getElementById("item-list").innerHTML=userInput;
console.log(toDoItems);
}
</script>
</head>
<body>
<h1>My Tasks</h1>
<button id="addItem" onclick="myFunction()">Add item</button>
<div id="item-list">
</div>
</body>
</html>
The Code above has an drawback: It erases the old value of userInput when you enter a new value in prompt().
I propose:
document.getElementById("item-list").innerHTML +=userInput+"";
Vu

Passing javascript created table from on html to another html

Edit: problem solved! Credits to #Thennarasan and #SiamakFerdos ,you have my deep gratitude!
Tips: when you are not sure if you get the value you intended to, try using
console.log(your intended value)
to check for it!
I am working on project and I need to pass a table from one html to another.
Whole process:
I want to create a html file to accept a number from the user as an input to produce a multiplication table.
Create an external javascript file that should have a function to generate the multiplication table.
Javascript function should contain array variables and loops to perform the operation.
Use appropriate user message using alert method.
Call the function when the user hits Generate Table button and forward results to another html page.
The following is what I have so far:
//This is the Calculation.js
function DisplayTable() {
var baseNumber = parseInt(document.getElementById("baseNumber").value);
var countMult = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var createMultTable = "<table border='1'>"
document.write(createMultTable);
//This will create the table
//First column is user input, second column is multplier from 1 to 10, third column is results.
for (var row = 0; row < 10; row++) {
document.write('<tr>' + '</tr>');
document.write('<td>' + baseNumber + '</td>' + '<td>' + countMult[row] + '</td>' + '<td>' + baseNumber * countMult[row] + '</td>');
}
createMultTable += "</table>";
document.write(createMultTable);
}
document.getElementById("newTable").innerHTML = createMultTable;
<!DOCTYPE html>
<html>
<!-- This is the Input.html, it gets a table from Calculation.js and pass it to TableGetter.html -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multiplication Table</title>
<link rel="stylesheet" href="Style.css" />
<script src="modernizr.custom.05819.js"></script>
<script type="text/javascript" src="Calculation.js"></script>
</head>
<body>
<header>
Multiplication Table
</header>
<article>
<h2>Multiplication Table</h2>
<form method="link" id="newTable" action="TableGetter.html">
Enter a number:
<input type="text" name="numInput" id="baseNumber" placeholder="Please enter an integer!">
<br>
<!-- <input id="multTable" type="submit" value="Submit" onclick="return DisplayTable();"> -->
<button type="button" name="button" onclick="DisplayTable();">Generate Table</button>
</form>
</article>
</body>
</html>
I am struggling at figuring out how to forward the result to TableGetter.html. I need help on writing the TableGetter.html as well as passing the table to TableGetter.html when I click Generate Table button in Input.html
Deep gratitude!
On TableGetter.html:
<script>
(function() {
document.getElementById("newTable").innerHTML = localStorage.getItem("table_html");
})();
</script>
And change your DisplayTable function:
function DisplayTable() {
var baseNumber = parseInt(document.getElementById("baseNumber").value);
var countMult = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var createMultTable = "<table border='1'>"
document.write(createMultTable);
//This will create the table
//First column is user input, second column is multplier from 1 to 10, third column is results.
for (var row = 0; row < 10; row++) {
document.write('<tr>' + '</tr>');
document.write('<td>' + baseNumber + '</td>' + '<td>' + countMult[row] + '</td>' + '<td>' + baseNumber * countMult[row] + '</td>');
}
createMultTable += "</table>";
localStorage.setItem("table_html", createMultTable);//ADD THIS LINE****
var url = 'TableGetter.html';//WRITE HERE YOUR RIGHT URL
window.location.href = url;
}
We need to make couple of changes, please exactly copy paste and check.
calculation.js
function DisplayTable() {
var baseNumber = parseInt(document.getElementById("baseNumber").value);
var countMult = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var createMultTable = "<table border='1'>"
document.write(createMultTable);
//This will create the table
//First column is user input, second column is multplier from 1 to 10, third column is results.
for (var row = 0; row < 10; row++) {
createMultTable += '<tr><td>' + baseNumber + '</td>' + '<td>' + countMult[row] + '</td>' + '<td>' + baseNumber * countMult[row] + '</td></tr>';
}
createMultTable += "</table>";
localStorage.setItem("table_html", createMultTable);//ADD THIS LINE****
var url = 'TableGetter.html';//WRITE HERE YOUR RIGHT URL
window.location.href = url;
}
if (window.location.pathname == "/C:/Users/Thennarasan/Desktop/js/TableGetter.html"){
var data = localStorage.getItem("table_html");
document.getElementById("newTable").innerHTML = data;
}
Note change the window.location.pathname of what you have.
input.html
<!DOCTYPE html>
<html>
<!-- This is the Input.html, it gets a table from Calculation.js and pass it to TableGetter.html -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multiplication Table</title>
<link rel="stylesheet" href="Style.css" />
<script src="modernizr.custom.05819.js"></script>
<script type="text/javascript" src="Calculation.js"></script>
</head>
<body>
<header>
Multiplication Table
</header>
<article>
<h2>Multiplication Table</h2>
<form method="link" id="newTable" action="TableGetter.html">
Enter a number:
<input type="text" name="numInput" id="baseNumber" placeholder="Please enter an integer!">
<br>
<!-- <input id="multTable" type="submit" value="Submit" onclick="return DisplayTable();"> -->
<button type="button" name="button" onclick="DisplayTable();">Generate Table</button>
</form>
</article>
</body>
</html>
TableGetter.html
<!DOCTYPE html>
<html>
<!-- This is the Input.html, it gets a table from Calculation.js and pass it to TableGetter.html -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Multiplication Table</title>
<link rel="stylesheet" href="Style.css" />
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<header>
Multiplication Table
</header>
<article>
<h2>Multiplication Table</h2>
<div id="newTable"></div>
</article>
<script type="text/javascript" src="Calculation.js"></script>
</body>
</html>
Run it, it will work as expected.

How to make jquery table which is refreshing itself in every 10 secs?

I am making admin portal, where admin can see the total number of current booking, for this we have to refresh table every 10 sec automatically and there will be also refresh button, which updates the table, I am using the JQuery, Ajax, Json, Spring MVC, Here is also one problem when I click on button It repeats the information. So please help me making these two things automatically refreshing Jquery table form database and Button which also refresh information without repeating the information, Thanks in advance for help and any suggestion,
Note: This is working code, thanks to Prog and ChrisH619
<!DOCTYPE html>
<html>
<head>
<title>Service for home - New Page - Next Generation of Service Provider - Admin Home Page</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<link href="assets/DT_bootstrap.css" rel="stylesheet" media="screen">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="vendors/flot/excanvas.min.js"></script><![endif]-->
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function fetchData(){
$(".data-contacts-js tbody").empty();
$.get("http://www.service4homes.com:8080/HomeServiceProvider/booking/getAllBookingDetails", function(data) {
$.each(data, function(i, contact) {
$(".data-contacts-js").append(
"<tr><td>" + contact.custId + "</td>" +
"<td>" + contact.custName + "</td>" +
"<td>" + contact.custMobile + "</td>" +
"<td>" + contact.custEmail + "</td>" +
"<td>" + contact.custAddress + "</td>" +
"<td>" + contact.Date + "</td>" +
"<td>" + contact.Time + "</td></tr>"
);
});
});
}
$(document).ready(function(){
$("#data-contacts-js > tbody").html("");
setInterval(function(){
fetchData();
},10000); // this will call your fetchData function for every 5 Sec.
});
$(document).ready(function(){
$("#data-contacts-js > tbody").html("");
$('#fetchContacts').click(function() {
fetchData();
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<!--/span-->
<div class="span9" id="content">
<div class="row-fluid">
<!-- block -->
<div class="block">
<div class="navbar navbar-inner block-header">
<div class="muted pull-left">Carpenter Services</div>
</div>
<div class="block-content collapse in">
<div class="span12">
<table class="data-contacts-js table table-striped" >
<thead>
<tr>
<th>ID</th>
<th>Customer Name</th>
<th>Customer Mobile</th>
<th>Customer Email</th>
<th>Address</th>
<th>Date</th>
<th>Time</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<button id="fetchContacts" class="btn btn-default" type="submit">Refresh</button>
</div>
</div>
<!-- /block -->
</div>
</div>
</div>
</div>
<!--/.fluid-container-->
<script src="vendors/jquery-1.9.1.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/datatables/js/jquery.dataTables.min.js"></script>
<script src="assets/scripts.js"></script>
<script src="assets/DT_bootstrap.js"></script>
<script>
$(function() {
});
</script>
</body>
</html>
Change your jQuery:
$(".data-contacts-js").append(
to
$(".data-contacts-js tbody").append( /*This nests properly in html*/
and before your
$.each(
remember to remove all the children :)
$(".data-contacts-js tbody").empty();
$.each(
If you then want to use exactly the same code to run (on a refresh, not just a fetch) with an abort:
$(document).ready(function(){
var getDataTimeoutId = null,
refetchTime = 10 /* time in seconds */
isFetching = false,
getData = function(){
if (isFetching) {return;}
if (getDataTimeoutId !== null){
window.clearTimeout(getDataTimeoutId);
getDataTimeoutId = null;
}
isFetching = true;
$.get(
/* ajax get */
).success(function(){
setDataTimeout(); /* Only auto re-get if there wasn't an error */
}).always(function(){
isFetching = false; /* always clear the status */
});
},
setDataTimeout = function(){
getDataTimeoutId = window.setTimeout(function(){
getData();
}, refetchTime * 1000);
};
$('#fetchContacts').click(function(){
getData();
);
setDataTimeout();
});
This means that the code will run every 10s, or a click. But won't hammer the server for multiple pending requests.
:)
Try below code: - Use setInterval
1st Step :
You should create one common function which will fetch all data form Database as below.
function fetchData(){
$(".data-contacts-js tbody").empty(); // this will remove all <tr>.
$.get("http://localhost:8080/Hotels/reservation/getAllBookingDetails", function(data) {
$.each(data, function(i, contact) {
$(".data-contacts-js").append(
"<tr><td>" + contact.custId + "</td>" +
"<td>" + contact.custName + "</td>" +
"<td>" + contact.custMobile + "</td>" +
"<td>" + contact.custEmail + "</td>" +
"<td>" + contact.custAddress + "</td>" +
"<td>" + contact.Date + "</td>" +
"<td>" + contact.Time + "</td></tr>"
);
});
});
}
Step 2:
Make function which will call function automatically in every 10 sec. using SetInterval as below.
$(document).ready(function(){
setInterval(function(){
fetchData();
},10000); // this will call your fetchData function for every 10 Sec.
});
Step 3:
Make one event function for refresh button click event and put this function in .ready() function.
$('#fetchContacts').click(function() {
fetchData();
});
You could simply use jQuery datatables. This is a fully featured jQuery plugin for tables with huge data sets, which supports things like refreshing in a given time interval. See here

Categories