Tengo un problema con el funcionamiento de mi web. Breve explicacion: genera una tabla donde muestra varios datos, extraídos de una BD, con un checkbox en cada fila. Los checkbox tienen la función de actualizar una columna en la BD, con el estado 1 o 0 (1 = checked). Ahora el error esta en que actualizo la tabla, (ya que ingresan nuevos datos en la BD todos los dias) con esta funcion:
$(document).ready(function() {
var pageRefresh = 6000; //6 s
setInterval(function() {
refresh();
}, pageRefresh);
});
function refresh() {
$('#contenido').load(location.href + " #contenido");
$('#Contador').load(location.href + " #Contador");
}
Actualiza esta tabla:
<table id="contenido" class="table-principal">
<thead>
<tr id="Tab-Tit" style="color: white">
<th scope="col">ENTREGADO</th>
<th scope="col">APELLIDO</th>
<th scope="col">NOMBRE</th>
<th scope="col">TARJETA</th>
<th scope="col">SERVICIO</th>
<th scope="col">DESCRIPCION</th>
<th scope="col">FECHA/HORA</th>
</tr>
</thead>
<tbody style="font-family: monospace;">
<?php include('query.php') ?>
</tbody>
</table>
Y aca estan los datos con los input:
<tr>
<td>
<input type="hidden" class="id-datos" name="ID" value="<?php echo $row[6] ?>">
<?php if ($row[7] == 1): ?>
<input class="habilitar task-chk" name="habilitar" type="checkbox" checked >
<?php endif;?>
<?php if($row[7] == 0): ?>
<?php if ($row[4] == "SE SOBREPASO EL MAXIMO DE ACCESOS"): ?>
<input type="checkbox" class="habilitar task-chk" name="habilitar" disabled>
<?php else: ?>
<input type="checkbox" class="habilitar task-chk" name="habilitar">
<?php endif; ?>
<?php endif; ?>
</td>
<td><?=$row[0]?></td>
<td><?=$row[1]?></td>
<td><?=$row[2]?></td>
<td><?=str_ireplace($serv_regular, $serv_nueva, $row[3])?></td>
<td class="datos-td"><?=str_ireplace($desc_regular, $desc_nuevo, $row[4])?></td>
<td><?=$row[5];?></td>
</tr>
Al activarse la función a los 6s (la que actualiza), deja de funcionarme este script:
document.querySelectorAll(".habilitar").forEach((fila) => {
fila.addEventListener("change", (e) => {
const id = document.querySelector('.id-datos').value
const formdata = new FormData();
if (e.target.checked) {
let habilitar = 1;
formdata.append("ID", id);
formdata.append("habilitar", habilitar);
console.log(habilitar);
console.log(`El id es ${id}`);
fetch("http://localhost:8080/Gestion_de_Comedores/Comedores_Totales/TEST/archivo.php", {
method: 'POST',
body: formdata,
})
.then((data) => {
console.log("Enviado correctamente");
})
.catch((error) => {
throw error;
});
} else {
let habilitar = 0;
formdata.append("ID", id);
formdata.append("habilitar", habilitar);
console.log(habilitar);
console.log(`El id es ${id}`);
fetch("http://localhost:8080/Gestion_de_Comedores/Comedores_Totales/TEST/archivo.php", {
method: 'POST',
body: formdata,
})
.then((data) => {
console.log("Enviado correctamente");
})
.catch((error) => {
throw error;
});
}
});
});
He visto que la mejor manera de resolver esto, es con WebSocket, pero lo desconozco y aun no me he metido en ese tema. Entonces mi duda es, como podría resolver este tema? He intentado cambiar la actualización con Ajax, pero aún no lo pude hacer funcionar, ya que no lo entiendo, soy nuevo con Ajax. Si pudiera solicitarles una ayuda, os agradeceré
EDIT:
Asi quedo el JS: Gracias por la ayuda.
const table = document.getElementById('contenido');
contenido.addEventListener("change", (event) => {
const formdata = new FormData();
const id = event.target.dataset.id
if (event.target.checked) {
let habilitar = 1;
formdata.append("ID", id);
formdata.append("habilitar", habilitar);
console.log(habilitar);
console.log(`El id es ${id}`);
fetch("http://localhost:8080/Gestion_de_Comedores/Comedores_Totales/TEST/archivo.php", {
method: 'POST',
body: formdata,
})
.then((data) => {
console.log("Enviado correctamente");
})
.catch((error) => {
throw error;
});
} else {
let habilitar = 0;
formdata.append("ID", id);
formdata.append("habilitar", habilitar);
console.log(habilitar);
console.log(`El id es ${id}`);
fetch("http://localhost:8080/Gestion_de_Comedores/Comedores_Totales/TEST/archivo.php", {
method: 'POST',
body: formdata,
})
.then((data) => {
console.log("Enviado correctamente");
})
.catch((error) => {
throw error;
});
}
});
Y los Inputs:
<td>
<input type="hidden" class="id-datos" name="habilitar" value="<?php echo $row[6] ?>">
<?php if ($row[7] == 1): ?>
<input class="habilitar task-chk" data-id="<?=$row[6]?>" name="habilitar" type="checkbox" checked >
<?php endif;?>
<?php if($row[7] == 0): ?>
<?php if ($row[4] == "SE SOBREPASO EL MAXIMO DE ACCESOS"): ?>
<input type="checkbox" class="habilitar task-chk" name="habilitar" disabled>
<?php else: ?>
<input type="checkbox" class="habilitar task-chk" data-id="<?=$row[6]?>" name="habilitar">
<?php endif; ?>
<?php endif; ?>
</td>