i have a Json data file where data is updating every second. i want to show data in Html page of my website in real time without loading page. i'm beginner in javascript i'm just learning please Help me. thanks in advance.
Here is My Json data file: Here
Here is My Html table Page (Result): Here
i want to show data in real time without loading page like stock price update.
please help.
<!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://code.jquery.com/jquery-3.5.1.js">
</script>
<!-- CSS FOR STYLING THE PAGE -->
<style>
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}
h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans',
'Gill Sans MT', ' Calibri',
'Trebuchet MS', 'sans-serif';
}
td {
background-color: #E4F5D4;
border: 1px solid black;
}
th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}
td {
font-weight: lighter;
}
</style>
</head>
<body>
<section>
<h1>My Google Sheet Table</h1>
<!-- TABLE CONSTRUCTION-->
<table id='mytable'>
<!-- HEADING FORMATION -->
<tr>
<th>Date</th>
<th>Name</th>
<th>Phone Number</th>
<th>Months</th>
</tr>
<script>
$(document).ready(function () {
// FETCHING DATA FROM JSON FILE
setInterval(function () {$.getJSON("JsonDataFileLink",
function (data) {
var content = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
content += '<tr>';
content += '<td>' +
value.SN + '</td>';
content += '<td>' +
value.Name + '</td>';
content += '<td>' +
value.Phone + '</td>';
content += '<td>' +
value.Months + '</td>';
content += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#mytable').append(content);
});
}, 3000);
});
</script>
</section>
</body>
</html>
I added your json file url to fetchData() to download the correct file and then I added a callback to be invoked when the data fetched is ready to be processed.
Data Transform: from array of objects to table rows
The transformation is a chain of map and reduce as follows...
Map (over json array of objects):
Iterates over the objects found in the json array and for each one of them it will return a new <tr> element mapped to the corresponding json object in the array.
Reduce (over the fields expected to be found in the object):
The reduction begins from the cols array telling the name of the properties that will be found in the json objects array in the same order they are wished to be displayed.
It just iterates over them, grabs the current value that gets embedded in a new <td> that gets appended to the new <tr>
Each reduce call will just return a new <tr> object as that.
Once we have the final map:
The final result is rows that just are appended to the table tbody once the processing is over.
Attention!
I see the json returned from that url isn't always the same. The date property is changing and some items at the end are empty sometimes.
Automatic refresh
I spent so much thoughts doing the data fetch algorithm that I was ignoring yours already worked and you just needed the refresh of data every once in a while without actually reloading the page.
So here I used setTimeout that will call after a given delay (pollingDelay default at 3000ms) the fetchData and at each iteration, after the table gets refreshed, it calls again the same setTimeout and updates the last time data was updated.
const pollingDelay = 3000;
function fetchData(refreshTable) {
url = 'https://script.googleusercontent.com/macros/echo?user_content_key=zASWVI1B2eWR37WJ_8Pn0h5WCuVP_1udOD8ZY6sMSzTfAo55CT4-ovYqEXJO5ZtrHrBeT9cYNecnp-Gzuq8TCmDVQfQQO1qjm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnMs1tm11-lp-Q13okfTSX_i5IzvU5JZnhqqg8H90dlfD5jU3SrNArGaMaXSvzMBh2h5A-lJ1RFia7VipeMnCxQqExfB7Qd_-iQ&lib=MVoeqw6DJ9bzix14T3i_S_jbsQ0CRhLAj';
$.getJSON(url, function(data) { refreshTable(data) });
}
//callback to be passed at fetchData
const cb = (data)=>{
//json object properties in the order how the are wished to be displayed on table
const cols = ['SN', 'Name', 'Phone', 'Months'];
var rownum = 0;
//maps the data items to table rows
const rows = data.map( entry => {
//creates a table row using reduce over cols
const newrow = cols.reduce(
(row, col) => { return $(row).append( $('<td>').text(entry[col]) ); }, $('<tr>')
);
//adds the data attribute data-rownum on the <tr>
newrow[0].dataset.rownum = ++rownum;
//returns the new row
return newrow;
});
//empties table and appends new row
$('#mytable tbody').empty().append(rows);
//updates the time at which the table was refreshed
const now = new Date();
$('#refresh').text(`Data refreshed at: ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`);
//set a new timer before calling again the fetchData()
setTimeout(fetchData(cb), pollingDelay)
}
$(document).ready(function() {
setTimeout(fetchData(cb), pollingDelay)
});
#refresh{
border: solid;
text-align: center;
font-size: 3rem;
}
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}
h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans', 'Gill Sans MT', ' Calibri', 'Trebuchet MS', 'sans-serif';
}
td {
background-color: #E4F5D4;
border: 1px solid black;
}
th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}
td {
font-weight: lighter;
}
tr:before{
content: attr(data-rownum);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<section>
<div id="refresh"></div>
<h1>My Google Sheet Table</h1>
<table id='mytable'>
<thead>
<th>Date</th>
<th>Name</th>
<th>Phone Number</th>
<th>Months</th>
</thead>
<tbody>
<tr>
<td colspan="4">Loading... please wait</td>
</tr>
</tbody>
</table>
</section>
</body>
Related
I have a Json Url which consists of data and in that data I want to print "title , date and notes separately but it is only showing [object object]...
I want to print data that is present inside the "events" list that have 'title' , 'date' and 'notes'
The link to Json file :- https://www.gov.uk/bank-holidays.json
I tried using events/title but it also does not work , I am new in javascript and I think I am doing a basic mistake :(
Thanks in advance
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GFG User Details</title>
<!-- INCLUDING JQUERY-->
<script src=
"https://code.jquery.com/jquery-3.5.1.js">
</script>
<!-- CSS FOR STYLING THE PAGE -->
<style>
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}
h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans',
'Gill Sans MT', ' Calibri',
'Trebuchet MS', 'sans-serif';
}
td {
background-color: #E4F5D4;
border: 1px solid black;
}
th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}
td {
font-weight: lighter;
}
</style>
</head>
<body>
<section>
<h1>Display Table</h1>
<!-- TABLE CONSTRUCTION-->
<table id='table'>
<!-- HEADING FORMATION -->
<tr>
<th>notes</th>
<th>title</th>
<th>date</th>
<th>Division</th>
</tr>
<script>
$(document).ready(function () {
// FETCHING DATA FROM JSON FILE
$.getJSON("https://www.gov.uk/bank-holidays.json",
function (data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
student += '<tr>';
student += '<td>' +
value.events + '</td>';
student += '<td>' +
value.date + '</td>';
student += '<td>' +
value.notes + '</td>';
student += '<td>' +
value.division + '</td>'
student += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#table').append(student);
});
});
</script>
</section>
</body>
</html>
So this solves your problem #maddy.
the issue was the what you were accessing. you had to access the events array inside of the object. so here is a sample
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GFG User Details</title>
<!-- INCLUDING JQUERY-->
<script src=
"https://code.jquery.com/jquery-3.5.1.js">
</script>
<!-- CSS FOR STYLING THE PAGE -->
<style>
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}
h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans',
'Gill Sans MT', ' Calibri',
'Trebuchet MS', 'sans-serif';
}
td {
background-color: #E4F5D4;
border: 1px solid black;
}
th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}
td {
font-weight: lighter;
}
</style>
</head>
<body>
<section>
<h1>Display Table</h1>
<!-- TABLE CONSTRUCTION-->
<table id='table'>
<!-- HEADING FORMATION -->
<tr>
<th>notes</th>
<th>title</th>
<th>date</th>
<th>Division</th>
</tr>
<script>
$(document).ready(function () {
// FETCHING DATA FROM JSON FILE
$.getJSON("https://www.gov.uk/bank-holidays.json",
function (data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
// map the events array in value to have access to the required object
$.each(value.events, function(key1, val) {
student += '<tr>';
student += '<td>' +
val.notes + '</td>';
student += '<td>' +
val.title + '</td>';
student += '<td>' +
val.date + '</td>';
student += '<td>' +
value.division + '</td>'
student += '</tr>';
});
});
//INSERTING ROWS INTO TABLE
$('#table').append(student);
});
});
</script>
</section>
</body>
</html>
[object object] is the data-type of the data you are fetching. To get the actual data, you would need to parse the json-data. (parse: unpack it)
When you fetch something over the internet (at least with http-api), you get a response, but that response can't send javascript objects, so you would use a function to stringify it (example: JSON.stringify(data)).
Javascript's built-in JSON-object has a the methods needed to do so.
To access this data when it is fetched, use JSON.parse(data)
I am showing data in a table dynamically in a table, I grt json data and show in html table dynamically. There is a card in html with that table, so I want to show each tr data in that card after 15 second means on load the first tr data shows in card and after 15 seconds the second tr data show in that same card and first tr data remove. I want to show each tr data in that card every 15 seconds
My code
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<head></head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style type="text/css" media="all">
body {
text-align: center;
box-sizing: border-box;
}
.card {
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
width: 200px;
padding: 10px;
margin: 10px;
}
.tr {
background: blue;
color: white;
transition: background .3s;
}
.table {
border-collapse: collapse;
border: 1px solid #ddd;
}
.table td {
padding: 10px 15px;
}
</style>
</head>
<body>
<div class="card">
<span id="value">25 </span><span id="unit">ppm</span>
<p id="parameter">Sodium Oxide</p>
</div>
<div class="table-responsive">
<table class="table" border="1">
<thead>
<tr>
<th scope="col">Parameter</th>
<th scope="col">Alias</th>
<th scope="col">Cordinates</th>
<th scope="col">Location</th>
</tr>
</thead>
<tbody id="scroll">
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON('./data.json', function(data) {
console.log(data)
var tdata = '';
$.each(data, function(key, value) {
console.log(value.deviceId)
tdata += '<tr>' + '<td>' + value.deviceId + '</td>' + '<td>' + value.aliasname + '</td>' + '<td>' + value.cordinates + '</td>' + '<td>' + value.location + '</td>' + '</tr>'
})
})
})
</script>
</body>
</html>
You need to call each DOM modification after a setTimeout. Here, I use async/await syntax:
const tbody = $('#scroll');
const sleep = (millis) => new Promise( resolve => setTimeout(resolve, millis));
$.getJSON('./data.json', async function(data) {
console.log(data);
// Forever loop over the received values
while(1) {
// For each value in data, replace table data
// with new tr containing data's value
for(const value of data) {
console.log(value.deviceId);
tbody.html(`<tr><td>${value.deviceId}</td><td>${value.aliasname}</td><td>${value.cordinates}</td><td>${value.location}</td></tr>`);
await sleep(15_000);
}
}
});
I have an HTML file that statically displays my school's schedule. How can I get table rows to change background color throughout the day based on time? I want the homeroom row to have a different background color only during homeroom and then return to normal when the row for first period has the different background color. And so on throughout the day.
<!DOCTYPE html>
<html>
<head>
<title>Schedule 1</title>
<style>
body {
background-color: black;
color:white;
text-align: center;
}
table, th, td {
color: black;
background-color: white;
text-align: center;
border: 2px solid black;
border-collapse: collapse;
font-size: 25px;
margin: auto;
padding: 5px;
}
th {
width: 300px;
height: 40px;
}
td:nth-child(1) {
width: 80px;
}
td:nth-child(2) {
width: 160px;
}
.table {
height: 500px;
}
</style>
</head>
<br><br>
<h1 style="color:white; bgcolor:black">SCHEDULE 1</h1>
<div class="table">
<table class="schedule">
<tr> <th width="300" colspan="2">REGULAR</th> </tr>
<tr> <td>HR</td><td>8:04 - 8:17</td> </tr>
<tr> <td>1</td><td>8:21 - 9:06</td> </tr>
<tr> <td>2</td><td>9:10 - 9:55</td> </tr>
<tr> <td>3</td><td>9:59 - 10:44</td> </tr>
<tr> <td>4</td><td>10:48 - 11:33</td> </tr>
<tr> <td>5</td><td>11:37 - 12:22</td> </tr>
<tr> <td>6</td><td>12:26 - 1:11</td> </tr>
<tr> <td>7</td><td>1:15 - 2:01</td> </tr>
<tr> <td>8</td><td>2:05 - 2:50</td> </tr>
</table>
</div>
</body>
</html>
You could do something similar to this, this uses jQuery. In your javascript, find out whether it is day or night (you could check for more times if you want) then depending on the result, update your dom styles. (This is in 24 hour format, you can change it to 12 hour format to make your if/else statements easier like this: ((hourCompare + 11) % 12 + 1)
var d = new Date();
var hourCompare = d.getHours();
if (hourCompare >= 8 && hourCompare <= 22) {
//day time
$('.tableCell').css("background-color", "yellow");
} else {
//night time
$('.tableCell').css("background-color", "blue");
}
I put together a jsfiddle for you. In order to get the correct colors, you will essentially have to write an if statement for each hour that you want to find and update the colors like I did in the fiddle. I wrote it to check for time updates every 3 seconds with setInterval. https://jsfiddle.net/zu588wjr/1/
I want the 'adult' column moved to the last position (on the right) in the table, but the table is interactive, the number of columns is not fixed, and sometimes, there will be no 'adult' column.
Please help
Here's the table:
table.tableizer-table {
font-size: 12px;
border: 1px solid #CCC;
font-family: Arial, Helvetica, sans-serif;
}
.tableizer-table td {
padding: 4px;
margin: 3px;
border: 1px solid #CCC;
}
.tableizer-table th {
background-color: #104E8B;
color: #FFF;
font-weight: bold;
}
<table class="tableizer-table">
<thead><tr class="tableizer-firstrow"><th></th><th>adult</th><th>embryo</th><th>lava</th><th>pupa</th></tr></thead>
<tbody>
<tr><td>AAEL006466-RA</td><td>ns</td><td>ns</td><td>**</td><td>ns</td></tr>
<tr><td>AAEL006466-S2</td><td>***</td><td>ns</td><td>ns</td><td>ns</td></tr>
<tr><td>AAEL006466-S4</td><td>***</td><td>ns</td><td>*</td><td>ns</td></tr>
</tbody>
</table>
This function will reorder the columns so that the 'adult' column is put last (if it is present in any position in the table).
It does presume that there is AT MOST only one column headed 'adult' (having no 'adult' column is fine though):
$(function() {
function reorderTable() {
var adultCol;
var $headerCells = $(".tableizer-firstrow").children();
$headerCells.each(function(idx, el) {
var title = (el.textContent || el.innerText || "").toLowerCase();
if (title === 'adult') adultCol = idx;
});
if (adultCol) { // adult column is present
$(".tableizer-table tr").each(function(idx, el) {
$(this).append($(this).children().eq(adultCol));
});
}
};
reorderTable();
});
table.tableizer-table {
font-size: 12px;
border: 1px solid #CCC;
font-family: Arial, Helvetica, sans-serif;
}
.tableizer-table td {
padding: 4px;
margin: 3px;
border: 1px solid #CCC;
}
.tableizer-table th {
background-color: #104E8B;
color: #FFF;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tableizer-table">
<thead>
<tr class="tableizer-firstrow">
<th></th>
<th>adult</th>
<th>embryo</th>
<th>lava</th>
<th>pupa</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAEL006466-RA</td>
<td>ns</td>
<td>ns</td>
<td>**</td>
<td>ns</td>
</tr>
<tr>
<td>AAEL006466-S2</td>
<td>***</td>
<td>ns</td>
<td>ns</td>
<td>ns</td>
</tr>
<tr>
<td>AAEL006466-S4</td>
<td>***</td>
<td>ns</td>
<td>*</td>
<td>ns</td>
</tr>
</tbody>
</table>
EDIT Here's an explanation of how it works...
$(function() { // this waits for DOM to load fully before executing
function reorderTable() {
var adultCol; // this will be the column number that has the 'adult' header
var $headerCells = $(".tableizer-firstrow").children(); // gets the collection of <th> cells
$headerCells.each(function(idx, el) { // runs a function on each <th> cell
// The following is equivalent to writing $(el).text().toLowerCase() -
// to get the inner text so that we can compare it to our search phrase.
// But it is more entertaining to write and will run faster than jQuery's fn.
// It's job is to handle differences between browsers, and to ignore case for the comparison later
var title = (el.textContent || el.innerText || "").toLowerCase();
if (title === 'adult') adultCol = idx; // if we have a match, remember the column #
});
if (adultCol) { // run only if we found the `adult` column index (i.e. it is not null or undefined)
$(".tableizer-table tr").each(function() { // loop over EVERY table row (so both header and body)
// `this` is the current row, and $(this).append(...) will move an element (cell)
// to the last position in that row.
// the inner part says give me the nth cell to move.
// The nth cell being the 'adult' column.
$(this).append($(this).children().eq(adultCol));
});
}
};
reorderTable(); // execute the above function
});
Try the following code:
$(function() {
let firstColumnHeader;
let findPosToMove = $("table").find('tr')[0].cells.length - 2;
jQuery.each($("table tr"), function(index, value) {
if(index === 0){
firstColumnHeader = ($(this).children(":eq(1)")[index].innerText);
}
if(firstColumnHeader == 'adult'){
for(var i = 0; i < findPosToMove; i++){
$(this).children(":eq(1)").before($(this).children(":eq("+(findPosToMove+1)+")"));
}
}
});
});
table.tableizer-table {
font-size: 12px;
border: 1px solid #CCC;
font-family: Arial, Helvetica, sans-serif;
}
.tableizer-table td {
padding: 4px;
margin: 3px;
border: 1px solid #CCC;
}
.tableizer-table th {
background-color: #104E8B;
color: #FFF;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tableizer-table">
<thead><tr class="tableizer-firstrow"><th></th><th>adult</th><th>embryo</th><th>lava</th><th>pupa</th></tr></thead>
<tbody>
<tr><td>AAEL006466-RA</td><td>ns</td><td>ns</td><td>**</td><td>ns</td></tr>
<tr><td>AAEL006466-S2</td><td>***</td><td>ns</td><td>ns</td><td>ns</td></tr>
<tr><td>AAEL006466-S4</td><td>***</td><td>ns</td><td>*</td><td>ns</td></tr>
</tbody>
</table>
I am creating a spreadsheet type program out of table cells and AngularJS and I would like to color my input cells based on the user's uploaded file.
I have an array that contains all of the user's data that I iterate through, and pending a match with some regular expressions, some data is pushed into a "red array" and a "blue array". I then have a function that is to be called when the original array's info is put into the spreadsheet. This function checks to see if the info being placed is in either the red or blue array, and will then color the input box red or blue (or green if no match is found.)
This coloring function is supposed to return a string which can be used as either the id or class of the input tag, and in the CSS, it colors the tag based on this returned name.
However, I can't seem to figure out the correct way of coloring the input tag. My input boxes remain the default white.
<script>
...
var blue = ["blue1","blue2","blue3"];
var red = ["red1","red2","red3"];
var allData = [["red1","misc1","misc2"],["blue1","blue2","blue3"],["red2","red3","misc3"]];
var makeColors = function(data){
if( data in red){
return "red";
}
else if( data in blue){
return "blue";
}
else{
return "green";
}
};
//creates the spreadsheet
sheet= function($scope, $parse){
$scope.columns = ["col1","col2","col3"]
$scope.rows = allData.length;
$scope.cells = {};
$scope.values = allData;
};
</script>
<div ng-app ng-controller="sheet">
<center><table>
<tr class="column-label">
<td ng-repeat="column in columns">{{column}}</td>
<tr ng-repeat="value in values">
<td class="row-label" ng-repeat="data in value">
<div id="{{data}}">
<input type="text" value="{{data}}" class="makeColors({{data}})">
</div>
</td>
</tr>
</table></center>
</div>
<style>
input{
font-size: 10pt;
position: absolute;
height: 1.2em;
height: 14pt;
overflow: hidden;
padding-left: 4pt;
border: none;
width: 80px;
}
table{
border-collapse: collapse;
}
td > div {
height:16pt;
width:2px;
}
td {
border: 1px solid #0EE;
width:85px;
}
.column-label >td, .row-label{
text-align:center;
background: #EEE;
}
.row-label {
width: 2em;
}
input.red{
background-color: red;
}
input.blue{
background-color: blue;
}
input.green{
background-color: green;
}
</style>
Your problem is on this line:
class="makeColors({{data}})"
You can't do it like that. Here is a fiddle where I'm using a map() to solve it: http://jsfiddle.net/W5aED/
To explain further the problem, the code outside {{ }} is not executed by angular (I mean the makeColors( part) and even if it were that is not the correct way to execute a javascript function.