Django updates view based on database - javascript

My issue seems pretty simple but I found it difficult since I'm extremely new to HTML / CSS / Django.
I have a postgresql database that is being updated continuously by another microservice. What I want to do is simply display the table in a HTML page (with https://datatables.net/ for example) and keep on updating it. I've found that we can create websocket connection when we reach the html page via channels but all the tutorial online are about chatbot.
I've managed to do it via a websocket/consumer:
class WSConsumer(WebsocketConsumer):
def connect(self):
self.accept()
while True:
#get the entire info from my db table
info = list(infoDB.objects.value())
self.send(json...(info..))
I keep on receiving the information in my HTML page (which is what I wanted), the only problem is I'm getting EVERYTHING from the table + I'm having hard time replacing correctly the initial table with the new one.
Here is my HTML page:
{% load static %}
<!DOCTYPE html>
<html lang="En">
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<title>Test</title>
</head>
<body>
<table id="table_id" class="table table-bordered" style="width:100%">
</table>
<script>
const socket = new WebSocket('ws://127.0.0.1:8000/ws/info_co/')
socket.onmessage = function(e){
const data = JSON.parse(e.data);
const table = document.getElementById("table_id");
for (var i = 0; i < data.message.length; i++)
{
var newRow = table.insertRow(table.length);
for (let key in data.message[i]){
var cell = newRow.insertCell(i);
cell.innerHTML = data.message[i][key];
}
}
var table = $('<table id="table_id" class="table table-bordered" style="width:100%">');
var tr = $('<tr>');
var arrheader = ['col 1', 'col 2', 'col 3','col 4', 'col 5','col 6'];
var array = data.message;
for (var j = 0; j < arrheader.length; j++) {
tr.append($('<th>').text(arrheader[j]));
}
table.append(tr);
for (var i = 0; i < array.length; i++) {
table.append(
$('<tr>').append(
$('<td>').text(array[i].elem_a),
$('<td>').text(array[i].elem_b),
$('<td>').text(array[i].elem_c),
$('<td>').text(array[i].elem_d),
$('<td>').text(array[i].elem_e),
$('<td style="color: green">').text(array[i].elem_f)
));
}
//table.css("border", "solid");
//document.querySelector('#table_id').innerHTML = table;
//document.getElementById('table_id').innerHTML = table;
$('#table_id').replaceWith(table);
//$('body').append(table);
}
$("#table_id").DataTable({
paging : true,
pagingLength: 10,
lengthChange: true,
autoWidth: true,
searching: true,
bInfo: true,
bSort : true,
});
</script>
</body>
</html>
Is there a more straightforward way of doing it ? Is it a good way to keep doing
list(infoDB.objects.value())
in a WHILE TRUE loop?

Related

I used HTML + JAVAScript, But i can see only JAVAScript

I used HTML and JAVAscript in one page.
But when i enter the site, and see.
I can see only JAVAscript, not HTML source.
There are few line of HTML string, and one jaascript which creat table
In the page, i can see only table, not few of HTML string
In the body code below,
Only i can see "script ~~/script" Only!
I can't see this below in the web page.
<br>
Back to admin main page <br>
Go to food list <br>
Go to food detail list <br>
This is the body code
<body>
<br>
Back to admin main page <br>
Go to food list <br>
Go to food detail list <br>
<script>showFoodList();</script>
</body>
this is a whole code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script language="javascript">
// this function is used to ask food to server and take a data with json
function showFoodList(){
var para = document.location.search;
fetch("http://gyrjs07.dothome.co.kr/what_to_eat/foodlist.php")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
creatTable(myJson);
});
}
function creatTable(data){
document.write("<table width='80%' border='1' style='margin: auto; text-align: center'>");
// for문 시작
for ( var i=0; i<data.length ; i++) {
document.write("<tr>"); // <tr> : 행추가
// 이중 for문 시작
for ( var j=0; j<data[i].length ; j++) {
var txt=data[i][j]; // 테이블각 셀에값을 출력
document.write("<td>"+ txt +"</td>"); // <td> : 열추가.
}
document.write("</tr>");
} //end for i
document.write("</table>"); // 테이블 태그를 닫는다.
}
</script>
</head>
<body>
<br>
Back to admin main page <br>
Go to food list <br>
Go to food detail list <br>
<script>showFoodList()</script>;
</body>
</html>
It happens because you use document.write method. It automatically calls document.open which removes all existing nodes in a document.
Documentation for Document.write() and Document.open()
Better approach is append children to some predefined node as it shown in snippet below.
const fakeApiResponse = [
["number", "name", "q-ty"],
["1.", "soda", "2"],
["2.", "beer", "3"],
["3", "pizza", "3"]
];
// this function is used to ask food to server and take a data with json
function showFoodList() {
// Emulate api call to get data
Promise.resolve(fakeApiResponse).then(function(myJson) {
creatTable(myJson);
});
}
function creatTable(data) {
// Get mountig node from HTML
const mountingPoind = document.getElementById("food-list");
// Create Table element and set some attributes
const table = document.createElement("table");
table.setAttribute("width", "80%");
table.setAttribute("border", "1");
table.setAttribute("style", "margin: auto; text-align: center");
// Start iterate over data to create table structure
for (let i = 0; i < data.length; i++) {
createTableRow(table, data[i]);
}
// Append table structure to mounting point
mountingPoind.appendChild(table);
}
// Creates row. Add text call createCell function to generate cells with data
// and append it to parent
function createTableRow(parent, rowData) {
const row = document.createElement("tr");
for (let j = 0; j < rowData.length; j++) {
createCell(row, rowData[j]);
}
parent.appendChild(row);
}
// Creates cell. Add text data to it and append it to parent
function createCell(parent, cellData) {
const cell = document.createElement("td");
cell.innerText = cellData;
parent.appendChild(cell);
}
showFoodList();
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<br />
Back to admin main page <br />
Go to food list <br />
Go to food detail list <br />
<br />
<div id="food-list"></div>
<script src="src/index.js"></script>
</body>
</html>

Pass variable in Google Apps Scriptlet to javascript

I just started coding with HTML and scriptlets within Google Sheets.
Trying to pass the array variable teacherArrayLean from the scriptlet (enclosed by <? ... ?>) to the <script>. However, <script> doesn't read the variable; when I replace the variable with constants, the scripts runs no problem so I know it's not the rest of the code.
Does anyone know how to use the variable in <script>? Thank you!
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
table, td, th {border: 1px solid black;}
table {border-collapse: collapse;}
th {text-align: left;}
</style>
</head>
<body>
<? var querySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('query');
var teacherArrayRaw = querySheet
.getRange(2, 4, querySheet.getLastRow() - 1, 1)
.getValues();
teacherArrayRaw.sort();
var teacherArrayLean = [];
teacherArrayLean.push(teacherArrayRaw[0]);
for(var n in teacherArrayRaw) {
if(teacherArrayLean[teacherArrayLean.length-1].toString().trim() != teacherArrayRaw[n].toString().trim()) {
teacherArrayLean.push(teacherArrayRaw[n]);
}
}
?>
<table id="calendar"></table>
<script>
var teacherArrayLean = [];
var table = document.getElementById("calendar");
var row = table.insertRow(0);
for (var col = 0; col < teacherArrayLean.length; col++) {
var cell = row.insertCell(col);
cell.innerHTML = teacherArrayLean[col];
}
</script>
</body>
</html>
You can do something like this:
<script>
var teacherArrayLean = JSON.parse("<?=JSON.stringify(teacherArrayRaw)?>");
....
</script>

JavaScript. Creating a dynamic table based on a user input

I'm trying to ask the user through a prompt for a number that is an: integer, greater than 0, and is numeric. I did that with a do while loop and seems to be working correctly. With that number I have to pass it to the function called "genTable" and create a table with a dynamic amount of rows based on what the user typed. However, with my current code I can't seem to get the table to appear on the page. Any ideas on where I went wrong and how to fix it?
<!DOCTYPE HTML>
<html>
<head>
<title>jsLoopDemo</title>
<!--
Honor Code: I acknowledge that this code represents my own work: CC
Date: July 6, 2017
-->
<meta charset="utf-8" />
<meta name="description" content="Create a chart with rows based on a number
user chose." />
<meta name="keywords" content="loop, row, dynamic" />
<meta name="author" content="" />
<script type="text/javascript">
do{
var numChose = prompt("Please enter an interger greater than zero.");
}while (isNaN(numChose) || numChose % 1 !== 0 || numChose < 1 );
function genTable(numChose)
{
var table = document.createElement("TABLE");
var tableBody = document.createElement("TBODY");
table.appendChild(tableBody);
var myTableDiv = document.getElementById("mytable");
for (var r = 0; r <= numChose; r++)
{
var tr = document.createElement("TR");
tableBody.appendChild(tr);
var td = document.createElement("TD");
tr.appendChild(td);
td.appendChild(document.createTextNode("Row " + r));
}
myTableDiv.appendChild(table);
}
</script>
</head>
<body>
<div id="mytable">
</div>
</body>
</html>
Two things:
You need to actually call the function after the prompt, so you need to add a line after your do while:
genTable(numChose);
That still won't work, since the DOM will not be ready (myTableDiv will be undefined), so you need to wrap your entire code in an event listener:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
Move the <script> code after the
<div id="mytable">
</div>
in <body> so that the element is rendered on DOM while table is being generated and call the function
genTable(numChose);
after you get the number from user.

Create Javascript rows with user input

How would you start writing a for loop for the code provided below:
<html>
<head>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/><br/><br/>
<table border="1" id="theTable">
</table>
<script type="text/javascript">
function makeTable(){
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
</script>
</body>
</html>
As I suspect this is homework I will no provider a full code answer but instead provide you with a few guide lines that hopefully will help you.
You have the html and the javascript, in order to create new html elements you need to use the document.createElement(type) function that will create a new element, in your case - td/th ?
Then you need to insert it into your table
You do that by obtaining the table(by id/type) - search the web for this one its very simple.
And then using the append method on is with the created element.
You do all this process with a normal for loop that will run until the .value of the input tags you have in your html (Again, search for how to obtain these values)
Good luck =]
Is this what you are looking for?
function makeTable(){
// Get values of rows/cols inputs
var rows = document.getElementById('rows').value;
var cols = document.getElementById('cols').value;
// Check the values are in fact numbers
if (!isNaN(rows) && !isNaN(cols)) {
// Get the table element
var table = document.getElementById('theTable');
// Iterate through rows
for (var r = 0; r < rows; ++r) {
// Create row element
var tr = document.createElement('tr');
// Iterate through columns
for (var c = 0; c < cols; ++c) {
// Create cell element
var td = document.createElement('td');
// Setting some text content
td.textContent = 'R: ' + r + ', C: ' + c;
// Append cell to row
tr.appendChild(td);
}
// Append row to table
table.appendChild(tr);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
Rows: <input name="rows" id="rows" type="text"/><br/>
Cols: <input name="cols" id="cols" type="text"/><br/>
<input type="submit" value="Make me a table!" onclick="makeTable();"/> <br/><br/>
<table border="1" id="theTable">
<script type="text/javascript">
function makeTable(){
var html = "";
var row=$('#rows').val();
var col=$('#cols').val();
for(var i=0; i<row; i++){
html+="<tr>";
for(var j=0;j<col; j++)
{
html+= '<td> Your data </td>';
}
html+="</tr>"
}
$('#theTable').html(html);
//Insert code here AND ONLY HERE!
//Write a for loop to create the number of rows specified in the "row" input field
//create a dom element for the row to be added to the table
}
</script>
</body>
</html>
I have kept it simple. Hope it helps.

How to detect negative values in a <td> of table in html?

I have a table in html, I am using Tangle framework to make the values look dynamic of that table.
What I want is to place a check on a specific <td> if its numeric value ever gets negative, the entire <tr> of that particular <td> should change its background color to Red.
Can this be done using java script or some simple lines of code may solve this problem?
Please help me doing this.
<html>
<head>
<style type="text/css">
td.negative { color : red; }
</style>
<script language="JavaScript" type="text/javascript">
<!--
function MakeNegative() {
TDs = document.getElementsByTagName('td');
for (var i=0; i<TDs.length; i++) {
var temp = TDs[i];
if (temp.firstChild.nodeValue.indexOf('-') == 0) temp.className = "negative";
}
}
//-->
</script>
</head>
<body>
<table id="mytable">
<caption>Some Financial Stuff</caption>
<thead>
<tr><th scope="col">Date</th><th scope="col">Money is good</th></tr>
</thead>
<tbody>
<tr><td>2006-05-01</td><td>19.95</td></tr>
<tr><td>2006-05-02</td><td>-54.54</td></tr>
<tr><td>2006-05-03</td><td>34.45</td></tr>
<tr><td>2006-05-04</td><td>88.00</td></tr>
<tr><td>2006-05-05</td><td>22.43</td></tr>
</tbody>
</table>
<script language="JavaScript" type="text/javascript">
<!--
MakeNegative();
//-->
</script>
</body>
I'd suggest:
var table = document.getElementsByTagName('table')[0],
cells = table.getElementsByTagName('td'),
hasNegative = 'hasNegative',
text = 'textContent' in document ? 'textContent' : 'innerText', num = 0;
for (var i = 0, len = cells.length; i < len; i++) {
num = parseFloat(cells[i][text]);
if (Math.abs(num) !== num) {
cells[i].parentNode.className += ' hasNegative';
}
}
JS Fiddle demo.
The rather bizarre means to determine negativity was a result of my previous, perhaps naive, check failing to differentiate between 0 and -0 (though I'm not quite sure whether negative-zero would pass, or fail, your criteria).

Categories

Resources