I want to update my table data after updating and keeping the datatables function working.
When editing a row from my table with modal, when refreshing the table the datatable function no longer works, such as pagination and search option.
Table:
<table class="table table-responsive" id="table6">
<thead>
<tr>
<th>Produto</th>
<th>Stock</th>
<th>Stock Minimo</th>
<th>Ação</th>
</tr>
</thead>
<tbody>
<?php do{ ?>
<tr id="<?php echo $produto3["Id"]; ?>">
<td><?php echo $produto3["Produto"]; ?></td>
<td><?php echo $produto3["Quantidade"]; ?></td>
<td><?php echo $produto3["Minimo"]; ?></td>
<td><button type="button" id="<?php echo $produto3["Id"]; ?>" data-id="<?php echo $produto3["Id"]; ?>" data-target="#add_data_Modal6" class="btn btn-warning btn-sm edit_data1" ><span class="glyphicon glyphicon-pencil"></span></button></td>
</tr>
<?php } while($produto3 = $result3->fetch_assoc()); ?>
</tbody>
</table>
Then I have the modal. When I save modal changes, I use the following js, where I refresh my table:
function inserir_registo10() {
var dadosajax = {
'Id': $("#Id1").val(),
'Produto': $("#Produto2").val(),
'DescricaoUnid': $("#DescricaoUnid1").val(),
'IdReqRec': $("#IdRec:checked").val(),
'Quantidade1': $("#Qtd2").val(),
'Quantidade': $("#Qtd1").val()
};
$.ajax({
url: './alterarproduto',
type: 'POST',
cache: false,
data: dadosajax,
error: function () {
$(".error_message").removeClass('hide');
},
success: function (result) {
$('.form10')[0].reset();
$("#add_data_Modal12").modal("hide");
$("#table6").load(" #table6 > *");
}
});
}
With the datatables function initially the table looks like this, where only shows ten records per page:
But when refreshing with this line in success:
$("#table6").load(" #table6 > *");
The datatables function no longer works and no longer shows the 10 records per page as shown in the image:
Although your question isn't completely clear, here are my thoughts: I think the issue is that once you render NEW content onto your page via the AJAX-ed response, the JavaScript functions that control the table - filtering and searching - no longer work. Is that correct?
My guess, based on your info: You need to re-initialize the table JavaScript after a successful AJAX call. Here's some pseudo code to demonstrate:
You probably have some JS code to initialize your table, something like:
$('.my-table').initialize()
Once you return the data via $.ajax and update the table, you simply need to re-run this initialization code in the success like:
$.ajax({
...
success: function (result) {
// Code to update your table here
// And now we can reinitialize:
$('.my-table').initialize()
}
});
I solved my problem as follows.
Within the success of ajax I destroy the table datatble, then make an asynchronous request and render the table again with datatable.
Code:
success: function(result)
{
$('.form10')[0].reset();
$("#add_data_Modal12").modal("hide");
$('#table6').dataTable().fnDestroy();
$.ajax({
url: './atualizarprodutosrececao',
type: 'get',
dataType: 'json',
success: function(data){
var linha = ``;
for(let item of data){
linha += `<tr id=${ item.Id }>
<td>${ item.Produto }</td>
<td>${ item.Quantidade }</td>
<td>${ item.Minimo }</td>
<td><button type="button" id="${ item.Id }" data-id="${ item.Id }" data-target="#add_data_Modal6" class="btn btn-warning btn-sm edit_data1" ><span class="glyphicon glyphicon-pencil"></span></button></td>
</tr>`;
}
$("#table6 tbody").html(linha);
$('#table6').dataTable({
"pagingType": "full_numbers",
"oLanguage": {
"sProcessing": "Aguarde enquanto os dados são carregados ...",
"sLengthMenu": "Mostrar _MENU_ registros por pagina",
"sZeroRecords": "Nenhum registro correspondente ao criterio encontrado",
"sInfoEmtpy": "Exibindo 0 a 0 de 0 registros",
"sInfo": "Exibindo de _START_ a _END_ de _TOTAL_ registros",
"sInfoFiltered": "",
"sSearch": "<span class='glyphicon glyphicon-search'></span>",
"oPaginate": {
"sFirst": "<span class='glyphicon glyphicon-fast-backward'></span>",
"sPrevious": "<span class='glyphicon glyphicon-backward'></span>",
"sNext": "<span class='glyphicon glyphicon-forward'></span>",
"sLast": "<span class='glyphicon glyphicon-fast-forward'></span>"
}
}
});
}
});
}
Related
I want to eliminate rows clicking on the button of each row. The JavaScript don't work right now. I can't find the problem. Any help? This part doesn't work Ajax, PHP scripts works well.
<script src="js/jquery-3.3.1.min.js"></script>
<script>
function eliminar() {
var idpedido = $(this).attr('id');
$.ajax({
type: 'post',
url: 'eliminar pedido.php',
data: idpedido: idpedido,
success: function (data) {
location.reload();
}
});
}
</script>
<table borde='2'>
<thead>
<tr>
<th>Idpedido</th>
<th>Pedido</th>
<th>Estado</th>
<th>Idempleado</th>
<th>Idcocinero</th>
</tr>
</thead>
<tbody>
<?php
// Bucle while que recorre cada registro y muestra cada campo en la tabla.
while ($columna = mysqli_fetch_array( $resultado ))
{ ?>
<tr name=pedidos id="<?php echo $columna ['idpedido']; ?>">
<td><?php echo $columna ['idpedido']; ?></td>
<td><?php echo $columna ['pedido']; ?></td>
<td><?php echo $columna ['estado']; ?></td>
<td><?php echo $columna ['idempleado']; ?></td>
<td><?php echo $columna ['idcocinero']; ?></td>
<td><button name="eliminar" type="button" class="btn btn-primary p-3 px-xl-4 py-xl-3" onclick="eliminar();" value="<?php echo $columna ['idpedido']; ?>"><span></span> Eliminar Pedido</button></td>
<?php } ?>
</tr>
</tbody>
</table>
I will not add any PHP to your code as you seem to be able to populate the table without issue.
I would add a class to the row, it does not have to be an ID as you can use the e.target, event target to target the closest row traversing up the DOM to get the row your button and content are in.
Query the selector using document.querySelectorAll('button[name="eliminar"') then remove it using an eventHandler, nested inside a loop, no unique ids are needed in this case as the button is identified by the event in the event handler. removeBtn.forEach(row => { to iterate through the nodeList of potential table row buttons, then target the events button using, row.addEventListener('click', removeRow). removeRow will be your call back passing the event into it as a parameter.
NOTE: This will ONLY affect the displaying of information in the front end, if you wish to remove info from your database, you will also need to run a query to your database and remove info there using PHP.
const removeBtn = document.querySelectorAll('button[name="eliminar"')
function removeRow(e) {
// you may want to add logic that confirms removal before actual removal...
// use the event.target and get the closest element with class of 'row'
//.remove() removes the element from the DOM
e.target.closest('.row').remove()
}
removeBtn.forEach(row => {
row.addEventListener('click', removeRow)
})
<table borde='2'>
<thead>
<tr>
<th>Idpedido</th>
<th>Pedido</th>
<th>Estado</th>
<th>Idempleado</th>
<th>Idcocinero</th>
</tr>
</thead>
<tbody>
<?php
// Bucle while que recorre cada registro y muestra cada campo en la tabla.
while ($columna = mysqli_fetch_array( $resultado ))
{ ?>
<tr class="row" name=pedidos id="<?php echo $columna ['idpedido']; ?>">
<td>
<?php echo $columna ['idpedido']; ?>test</td>
<td>
<?php echo $columna ['pedido']; ?>test</td>
<td>
<?php echo $columna ['estado']; ?>test</td>
<td>
<?php echo $columna ['idempleado']; ?>test</td>
<td>
<?php echo $columna ['idcocinero']; ?>test</td>
<td><button name="eliminar" type="button" class="btn btn-primary p-3 px-xl-4 py-xl-3" value="<?php echo $columna ['idpedido']; ?>">Eliminar Pedido</button></td>
<?php } ?>
</tr>
</tbody>
</table>
I'm doing crud (CREATE, READ, UPDATE, DELETE) table in PHP + JS + SQL and I want to do the next:
I have a table with users (I take this data from my DB):
When I click on the "Edit" icon (green edit icon), I can type on the values of my table.
I don't know how to get the exact position of the array (to show all of those users, I'm using an array, ofc) to save it in a variable for later do a query to update the information.
Do you know what I'm trying to say, guys?
Here is my code:
<table class='table table-bordered table-hover' class='display' style='width:100%; text-align: center;' id='tableTest'>
<thead>
<tr>
<th>Editar</th>
<th>Nombre</th>
<th>Apellido 1</th>
<th>Apellido 2</th>
<th>Email</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
<?php foreach ($res_table as $r){ ?>
<tr>
<td><span class="fas fa-edit editar grow" onclick="updateData(this)"></span></td>
<td><?php echo $r->usuario?></td>
<td><?php echo $r->apellido1?></td>
<td><?php echo $r->apellido2?></td>
<td><?php echo $r->email?></td>
<td><span class="fas fa-trash-alt grow" onclick="updateData(this)"></span></td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="contenedorForm">
</div>
And here is my JS.
// Función para actualizar los datos de la tabla.
function updateData(nodo){
var nodoTd = nodo.parentNode; //Nodo TD
var nodoTr = nodoTd.parentNode; //Nodo TR
var nodoContenedorForm = document.getElementById('contenedorForm'); //Nodo DIV
var nodosEnTr = nodoTr.getElementsByTagName('td');
var editData = nodosEnTr[0].textContent;
var usuario = nodosEnTr[1].textContent;
var apellido1 = nodosEnTr[2].textContent;
var apellido2 = nodosEnTr[3].textContent;
var email = nodosEnTr[4].textContent;
var opciones = nodosEnTr[5].textContent;
var nuevoCodigoHtml =
'<td><span class="fas fa-edit editar grow" onclick="updateData(this)"></span></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="usuario" id="usuario" value="' + usuario + '" size="20"></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="apellido1" id="apellido1" value="' + apellido1 + '" size="20"></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="apellido2" id="apellido2" value="' + apellido2 + '" size="20"></td>'+
'<td><input onblur="getIdInputFromDatabase()" type="text" name="email" id="email" value="' + email + '" size="20"></td>' +
'<td><span class="fas fa-trash-alt editar grow" onclick="updateData(this)"></span></td>';
nodoTr.innerHTML = nuevoCodigoHtml;
nodoContenedorForm.innerHTML =
'Pulse Aceptar para guardar los cambios o cancelar para cancelActionlos' +
'<form name = "formulario" action="general" method="get" onsubmit="capturarEnvio()" onreset="cancelAction()">' +
'<input class="boton" type = "submit" value="Aceptar">' +
'<input class="boton" type="reset" value="Cancelar">';
}
function getIdInputFromDatabase(){
alert("I NEED TO KNOW THE POSITION OF THE ARRAY WHERE I DID ON BLUR");
}
// Data tables.
$(function () {
$('#tableTest').DataTable({
"language": {"url": "//cdn.datatables.net/plug-ins/1.10.20/i18n/Spanish.json"},
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": false,
"autoWidth": false,
"scrollX": false
});
});
</script>
How Can I do this, guys? Can you help me? I searched on the DataTables API but Im lost.
Thank you in advance!
Have a good day!
As you have a field called ID you can store that in the HTML when you first build your table (in the <?php foreach ($res_table as $r){ ?> loop), this can be either as an attribute to the tr, eg
<tr data-id='<?php echo $r->id?>'>
or in a hidden td, eg
<td style='display:none;'><?php echo $r->id?></td>
(don't use style='display:none' use a css to hide it, just an example here to show it's hidden).
Then your edit can know which row is being edited by its ID (rather than row index, which may not match the DB ID)
var id = $(nodoTr).data("id")
or
var id = nodoTr[0].textContent;
You then need to pass that id to your inline edit, in some way, this could be by adding as a parameter to the onsubmit, eg:
'... onsubmit="capturarEnvio(' + id + ')" ...'
On some of my datatables doesn't show the sorting and search. The red boxes is what I want to display but I cant get them showing u on some of my tables. The datatables are exactly the same, I've copied the code but nothing changed. So I'm asking if someone has a solution for me?
Below you will see some of my javascript and html code:
--- javascript ---
$("#dataTablesFull, #dataTablesFull2, #dataTablesFull3, #dataTablesFull4").dataTable( {
"pageLength": <?php echo getConfigValue("table_records"); ?>,
"dom": '<"top"f>rt<"bottom"><"row dt-margin"<"col-md-6"i><"col-md-6"p><"col-md-12"B>><"clear">',
"buttons": [ 'copy', 'csv', 'excel', 'pdf', 'print' ],
"stateSave": true,
"fixedHeader": false,
"oLanguage": {
"sSearch": "",
"sEmptyTable": "<?php _e('Oops! Er is niets om weer te geven.'); ?>",
"sZeroRecords": "<?php _e('Niets gevonden'); ?>",
"sInfo": "<?php _e('Weergeven van: '); ?> _START_ <?php _e('tot'); ?> _END_ <?php _e('van'); ?> _TOTAL_ <?php _e('records.'); ?>",
"sInfoEmpty": "",
"oPaginate": {
"sNext": "<?php _e('Volgende'); ?>",
"sPrevious": "<?php _e('Vorige'); ?>",
"sFirst": "<?php _e('Eerste pagina'); ?>",
"sLast": "<?php _e('Laatste pagina'); ?>"
}
},
"columnDefs": [ { "orderable": false, "targets": -1 } ] }
);
--- html ---
<div class="table-responsive">
<table id="dataTablesFull" class="table table-striped">
<thead>
<tr>
<th>Naam</th>
<th>E-mail</th>
<th>Antwoord</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($contacts as $contact) { ?>
<tr>
<td>
<?php echo $name; ?>
</td>
<td>
<?php echo $email; ?>
</td>
<td>
<?php
if(empty($answer)) {
echo " -";
}
if(!empty($answer)) {
echo $answer;
}
?>
</td>
<td>
<?php
if($contact['status'] == 0) {
echo "Verzonden";
}
if($contact['status'] == 1) {
echo "Beantwoord";
}
?>
</td>
<td>
<div class='pull-right btn-group'>
<a href="#" onClick='#' class='btn btn-info btn-flat btn-sm'><i class='fa fa-eye'></i></a>
<a href="#" onClick='#' class='btn btn-danger btn-flat btn-sm'><i class='fa fa-trash-o'></i></a>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
For the buttons to appear you need "B" on the "dom" option (i.e. Buttons)
For the search bar to appear you need "f" in the "dom" option (i.e. filter)
For pagination you need "p" in the "dom" option. (i.e. pagination)
i.e.
$('#myTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
]
} );
Refer to https://datatables.net/reference/option/dom and https://datatables.net/extensions/buttons/
You seem to have them there but with extra styling applied, it could it be the case that the stylesheet that is being referred to is not loading (check via browser dev tools)
I have the following table where I have two buttons to delete and update.
When I delete it automatically removes the table row.
But when I edit the line and change the state, the user still sees the line, where it gets confusing because they don't know the lines that have already been edited and the ones left to edit.
So when changing state the row should also disappear from the table.
Code:
<div id="spoiler2" class="esconde">
<table class="table table-responsive" id="employee_table2">
<h1 style="font-size: 30px"><strong>Pedidos de Manutenção</strong></h1>
<thead>
<tr>
<th>Data</th>
<th>Valência</th>
<th>Descrição</th>
<th>Colaborador</th>
<th>Estado</th>
<th>Ação</th>
<th>Eliminar</th>
</tr>
</thead>
<tbody>
<?php do{ ?>
<tr id="<?php echo $produto2["Id"]; ?>">
<td><?php echo $produto2["DataRegisto"]; ?></td>
<td><?php echo $produto2["Destino"]; ?></td>
<td><?php echo $produto2["Descricao"]; ?></td>
<td><?php echo $produto2["nome"]; ?></td>
<td><?php echo $produto2["Estado"]; ?></td>
<td><button type="button" name="edit" data-id="<?php echo $produto2["Id"]; ?>" id="open_<?php echo $produto2["Id"]; ?>" data-target="#add_data_Modal2" class="btn btn-warning btn-sm edit_data2" ><span class="glyphicon glyphicon-pencil"></span></button></td>
<td><button class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-trash"></span></button></td>
</tr>
<?php } while($produto2 = $result2->fetch_assoc()); ?>
</tbody>
</table>
</div>
js:
$(document).on('click', '.edit_data2', function(){
var employee_id2 = $(this).data('id');
$.ajax({
url:"./editarmanutencao",
method:"POST",
cache: false,
data:{employee_id2:employee_id2},
dataType:"json",
success:function(data){
console.log(data);
$('#Id2').val(data.Id);
$('#Tratamento').val(data.Tratamento);
$('#Estado2').val(data.Estado);
$('#Prestador').val(data.Prestador);
$('#employee_id2').val(data.Id);
$('#insert2').val("Gravar");
$("#add_data_Modal2").modal("show");
}
});
});
function inserir_registo2()
{
var dadosajax = {
'Id' : $("#Id2").val(),
'DataTermino' : $("#DataTermino").val(),
'Tratamento' : $("#Tratamento").val(),
'Estado' : $("#Estado2").val(),
'Prestador' : $("#Prestador").val()
};
$.ajax({
url: './resolucaomanutencao',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$("#add_data_Modal2").modal("hide");
}
});
}
How can I remove the table row by changing ajax's success state?
If i understand correctly, you want to remove row from table after successful Edit operation.
If this is the case, you can use following code...
function inserir_registo2()
{
let rowToBeRemoved = $("#"+$("#Id2").val());
var dadosajax = {
'Id' : $("#Id2").val(),
'DataTermino' : $("#DataTermino").val(),
'Tratamento' : $("#Tratamento").val(),
'Estado' : $("#Estado2").val(),
'Prestador' : $("#Prestador").val()
};
$.ajax({
url: './resolucaomanutencao',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$("#add_data_Modal2").modal("hide");
if(<<Condition>>) // in case you want to validate something before removing row
{
rowToBeRemoved.remove();
}
}
});
}
Save a reference to the parent row before the ajax call (e.g. var row = $(this).closest('tr')) and then, on success, remove it by row.remove().
I am trying to update database records using ajax from the ajax response, getting success message but the actual database records are not updated at all. But it wonder how the ajax response should throw the success message while the query is not updating the database.
VIEW:
// AJAX code to update the database
// update marks when form is submitted
$('#updateMarks').on('submit',function(event) {
event.preventDefault();
var practical_mark = $("#mark_written").val();
var written_mark = $("#mark_practical").val();
var comment = $("#comment").val();
var mark_id = $("#mark_id").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
alert("success");
},
error: function(){
alert("Error");
},
});
});
<?php foreach($marks as $row2): ?>
<form method="post" role="form" id="updateMarks">
<tr>
<td class="text-center"><?php echo $student['name']; ?></td>
<td>
<!-- create two col table for marks category -->
<table class="table table-bordered table-hover toggle-circle">
<thead>
<tr>
<th data-toggle="true" class="text-center"><?php echo get_phrase('written_exam'); ?></th>
<th data-toggle="true" class="text-center"><?php echo get_phrase('practical_exam'); echo get_phrase('_(out_of_100)'); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><input type="number" value="<?php echo $row2['written_mark_obtained'];?>" id="mark_written" name="mark_written" class="form-control" /></td>
<td class="text-center"><input type="number" value="<?php echo $row2['practical_mark_obtained'];?>" id="mark_practical" name="mark_practical" class="form-control"/></td>
</tr>
</tbody>
</table>
<!-- end create two col table for marks category -->
</td>
<td class="text-center"><textarea class="form_control" id="comment" name="comment" rows="4" > <?php echo $row2['comment'] ?> </textarea></td>
<td class="text-center">
<input type="hidden" id="mark_id" name="mark_id" value="<?php echo $row2['mark_id'];?>" />
<button type="submit" class="btn btn-block btn-success btn-md"><i class="icon pe-pen" aria-hidden="true"></i><?php echo get_phrase('update'); ?></button>
</td>
</tr>
</form>
<?php endforeach; ?>
Controller:
function exam_marks_update(){
$data['written_mark_obtained'] = $this->input->post('written_mark');
$data['practical_mark_obtained'] = $this->input->post('practical_mark');
$data['comment'] = $this->input->post('comment');
$this->crud_model->update_student_marks($data, $this->input->post('mark_id'));
}
MODEL
function update_student_marks($data, $mark_id){
$this->db->where('mark_id', $mark_id);
$this->db->update('mark', $data);
}
Jquery ajax success callback function is always called if the request to server succeeds. You need to return response data from server to verify when database operation was successful or not. I have edited your code , this might work for you.
MODEL
function update_student_marks($data, $mark_id){
.....
return $this->db->update('mark', $data);
}
Controller::
function exam_marks_update(){
.....
if($this->crud_model->update_student_marks($data, $this->input->post('mark_id'))){
echo json_encode(array('success' => true));
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
}
View
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
dataType :'json',
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
if (response.success === true){
alert("success");
} else {
alert('failed');
}
},
error: function(){
alert("Error");
},
});
Your Controller retrieving inputs which doesn't exists... you need to pass your name, id as inputs and not the value which you echo... see as Controller:
function exam_marks_update(){
$data = array(
'written_mark_obtained' => $this->input->post('written_mark'),
'practical_mark_obtained' => $this->input->post('practical_mark'),
'comment' => $this->input->post('comment')
);
$this->db->where('mark_id', $this->input->post('mark_id'));
$this->db->update('mark', $data);
}
and change this:
var comment = $("#comment").val();
to
var comment = $("#comment").html();
As comment is textarea...