I have a query regarding passing data from a Python database to JavaScript.
The current code allows for accessing the data in JavaScript but only one row at a time can be passed.
#!le/usr/bin/env python3
import sys
import re
import datetime
import sqlite3
import json
import time
SQLDB = '/home/daylene/db/PiLN.sqlite3'
db = sqlite3.connect(SQLDB)
db.row_factory = sqlite3.Row
cursor = db.cursor()
sql = '''SELECT segment, dt, set_temp, temp, pid_output
FROM firing WHERE run_id=? ORDER BY dt;
'''
p = ((54),)
cursor.execute(sql, p)
columns = [column[0] for column in cursor.description]
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns,row)))
print(json.dumps(results[-1]))
And here is the corresponding JavaScript code:
<script>
$(document).ready(function () {
showGraph();
});
function showGraph()
{
$.ajax({
mimeType: 'application/json; charset=iso-8859-1',
url: 'data.cgi',
contentType: "application/json",
dataType: 'json',
method: 'POST',
async: false,
success: function (response)
{
var time = response["dt"];
var temp = response["temp"];
var chartData = {
labels: time,
datasets: [
{
label: 'time',
backgroundColor: '#49e2ff',
borderColor: '#46d5f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
data: temp
}
]
};
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartData
});
}
});
}
</script>
If I uncomment document.write(response);
and change it to print(json.dumps(results))
, it doesn't work. Nothing is returned with document.write(response);
.
I have tried adding this piece of code, which also did not yield the desired result:
results1 = []
for row in results:
results1.append(json.dumps(row))
print(results1)
Following that, when I added the next snippet of code, it also did not produce the expected outcome:
results1 = []
for row in results:
results1.append(json.dumps(row))
print(json.dump(results1))
This is the shortened output of print(results)
:
[{"segment": 4, "dt": "2020-07-09 19:58:55", "set_temp": 1145, "temp": 1145.02, "pid_output": 83.49}, {"segment": 4, "dt": "2020-07-09 19:59:24", "set_temp": 1145, "temp": 1145.15, "pid_output": 80.76}, ... ]
I would appreciate any guidance on how to solve this issue.