I have a table with a series of records, I frame with several checkboxes of them. I click on a button that updates the records, what it does is call a php script through Ajax as many times as I have selected records.
Well once finished, the page is reloaded with a window.location.reload (); and surprise of the records that I have marked, for example: 6 has only updated me 4 (these values are indicative because they are changing, sometimes even updates them all) The only way I have to see the information correctly updated is to reload the web page from the browser.
I put the code that I use for the Ajax request and the subsequent reload of the page:
$('#canviestat').on('show.bs.modal', function (event) { // Selection of id f the checkboxes of the checked rows
var arrayCod = new Array();
var arraySaldo = new Array();
$('#tableprod').find('tbody tr').each(function () { // Loop every rows of the table
var $button = $(event.relatedTarget); // Button that triggered the modal
var row = $(this);
var cod = (this.id);
var saldo;
if (row.find('input[type="checkbox"]').is(':checked')) { // Add the id_fichaje to array
console.log(cod);
arrayCod.push(cod);
arraySaldo.push(row.find("td[data-field='saldo']").text()); // Envío cálculo de saldo
}
});
if (arrayCod.length != 0){ // If array contents id then...
$('input[type="submit"]').prop('disabled', false);
$('#codigosSeleccionados').text(arrayCod.length + " codis seleccionats");
$('input[type="submit"]').click(function(event){
event.preventDefault();
var inputvalue = $(this).attr("value"); // Get the value of the input fields
$.each( arrayCod, function( key, value ) { // Loop arrayCod and call ajax to update estado
$.ajax({
url:"updateEstado.php",
type:"POST",
data:{"estado": inputvalue, "id_fichaje": value, "saldo": arraySaldo[key]},
dataType:"text",
success:function(data){
$('#canviestat').modal('hide'); //Close window modal
$('#tableprod').bootstrapTable('uncheckAll');
}
});
PHP Code:
<?php
session_start();
if(isset($_SESSION['username']) and $_SESSION['username'] != ''){
include("db_tools.php");
include("functions.php");
$conn = dbConnect("localhost", "5432", "-", "-", "-");
$estado = $_POST['estado'];
$estado = Estado($estado);
$id_fichaje = $_POST['id_fichaje'];
$saldo = $_POST['saldo'];
$username = $_SESSION['username'];
$query = "UPDATE produccion.estado SET usuario='{$username}', estado='{$estado}', fecha_mod=now() WHERE id_fichaje = '{$id_fichaje}'";
$result = pg_query($conn, $query);
pg_close($conn);
} else{
?>
<br>
<br>
<div class="row">
<div class="text-center">
<p class='errorLogin'>La sessió no està activa, si us plau login <a href="login.php">aquí</a></p>
</div>
</div>
<?php
}?>
UPDATE:
Updated jquery code.
I have detected that the debug console fails to send multiple records for the update:
/assets/jquery/jquery.min.js:4 XHR failed loading: POST " link " .
In the jquery code, what I do is go through all the selected checkboxes and send them to the post one by one, that is, in a loop.