-1
Problem: I need to do a real-time refresh Chart.js chart, but for that I’m having to update the data coming from the database with a refresh button, I need that as soon as the page loads the data every 30 seconds.
FILE CODE -> PHP (QUERY)
<?php include '../../Config/conexao.php'; include '../../Models/Grafico.php';
$sql = "SELECT * FROM energy"; $query = $con->prepare($sql); $query->execute();
setlocale(LC_TIME, 'Portuguese_Brazil'); $semana = date("d/m/Y", strtotime("- 7 days"));
$retorno = array();
$graf = new Grafico;
$dataBox[] = $graf->buscaDados($semana, $query, $retorno);
echo json_encode($dataBox); ?>
PHP CLASS CALLED IN FILE ABOVE
<?php
class Grafico
{
private $results;
public function buscaDados($semana, $query, $retorno)
{
while ($results = $query->fetch(PDO::FETCH_ASSOC))
{
if (date("d/m/Y", strtotime($results['DATA_REGISTRO'])) > $semana)
{
$retorno['semanal'][strtoupper(utf8_encode(strftime("%a", strtotime($results['DATA_REGISTRO']))))]
["HORARIO"] = date("H", strtotime($results['DATA_REGISTRO']));
$retorno['semanal'][strtoupper(utf8_encode(strftime("%a", strtotime($results['DATA_REGISTRO']))))]
["ENERGIA"] = $results["ENERGIA"];
}
}
return $retorno;
}
}
?>
FILE CODE -> CHART JS WITH REQUEST $.GET()
$('document').ready(()=>{
$.get("../Controllers/php/dashboard.php", function(dados, status) {
var valores = JSON.parse(dados);
var diasSemana = [];
var consumoSemanaEnergia = [];
var consumoSemanaEnergiaHorario = [];
$.each(valores, function(key, value)
{
$.each(value, function(chavePeriodo, consumo){
$.each(consumo, function(chaveEnergia, valor)
{
if (chavePeriodo = 'semanal')
{
diasSemana.push(chaveEnergia);
consumoSemanaEnergia.push(valor.ENERGIA);
consumoSemanaEnergiaHorario.push(valor.HORARIO);
}
});
});
});
grafico (diasSemana, consumoSemanaEnergia, consumoSemanaEnergiaHorario);
});
});
What do I do in this case? I’ve tried using a setInterval(), but video lessons only show with an input using $(element). keyup and in my case, the user wouldn’t do anything, no action, it would just be on the server. Anyone have any ideas? A help? A suggestion?
It is a slightly more complex problem, the Realtime back end structure, with a reactive language, would be perfect. However you could initially use a setinterval function in javascript, to trigger refresh every 30 seconds. https://www.w3schools.com/jsref/met_win_setinterval.asp
– Lenon S. De Paula
But how would I do that? Example:: currently I click the button, Submit calls the php file, php returns the json_encode from there jquery enters to separate the values in each array, then.... how do I do this?
– Braz Brz