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().
Related
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>"
}
}
});
}
});
}
I am trying to delete the table entry without opening the .php file using jQuery post.
The whole thing works without problems when I just use the usual html post form.
The alert(data) does not trigger, it only adds ".../?player_id_del=1" or whatever ID click into the URL.
What am I doing wrong?
Here is some of my index.php, i get the whole data from a database:
<table class = "table table-hover">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr>
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<form id="del-form">
<div>
<input type="number" id="player_id_del" name="player_id_del" value="<?php echo htmlspecialchars($player["PLAYER_ID"]); ?>" />
</div>
<div>
<button type="submit" id="submit-btn" class="btn btn-danger">Delete</button>
</div>
</form>
<script>
$("#submit-btn").click(function(){
$.post("deletePlayer.php", $("#del-form").serialize() , function(data) {
alert(data);
});
});
</script>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
Here is my deletePlayer.php:
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
echo "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
echo "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
?>
Thank You in advance for any help!
By default jQuery's click event reload the document so, you should try using,
$("#submit-btn").click(function(e){
e.preventDefault();
e.stopPropagation();
});
Also instead of $.post, try using $.ajax
There are many issues in your code
E.g IDs for form and delete input button are repeating (id of element should not be same it should be unique),
The following code is the tested and working.
<?php
//include DatabaseHelper.php file
require_once('DatabaseHelper.php');
//instantiate DatabaseHelper class
$database = new DatabaseHelper();
$response = array();
//Grab variable id from POST request
$player_id = '';
if(isset($_POST['player_id_del'])){
$player_id = $_POST['player_id_del'];
}
// Delete method
$error_code = $database->deletePlayer($player_id);
// Check result
if ($error_code == 1){
$response["success"] = 1;
$response["id"] = $player_id;
$response["message"] = "Player with ID: '{$player_id}' successfully deleted!'";
}
else{
$response["success"] = 0;
$response["message"]= "Error can't delete Player with ID: '{$player_id}'. Errorcode: {$error_code}";
}
echo json_encode($response);
?>
<table class = "table table-hover" id="mPlayersTabel">
<thead>
<tr>
<th>Player_ID</th>
<th>Username</th>
<th>First_Name</th>
<th>Last_Name</th>
<th>Rating</th>
<th>Country</th>
<th>Colour</th>
<th></th>
</tr>
</thead>
<tbody>
<? foreach($playerArray as $player):?>
<tr id= "<? echo $player["PLAYER_ID"]; ?>">
<td><? echo $player["PLAYER_ID"]; ?></td>
<td><? echo $player["USERNAME"]; ?></td>
<td><? echo $player["FIRST_NAME"]; ?></td>
<td><? echo $player["LAST_NAME"]; ?></td>
<td><? echo $player["RATING"]; ?></td>
<td><? echo $player["COUNTRY"]; ?></td>
<td><? echo $player["COLOUR"]; ?></td>
<td>
<div>
<button type="submit" player-id="<? echo $player["PLAYER_ID"]; ?>" class="btn btn-danger" >Delete</button>
</div>
</td>
</tr>
<? endforeach ?>
</tbody>
</table>
<script>
$(document).ready(function(){
$(".btn-danger").on("click touchend" , function(){
var id = $(this).attr("player-id");
$.ajax({
url: 'deletePlayer.php',
type: 'POST',
data: {
player_id_del: id
},
dataType: 'json',
success: function (response) {
//Add this line and try
response = JSON.parse(JSON.stringify(response));
alert(response['message']);
switch (response['success']) {
case 1:
$("#mPlayer" + response['id']).remove();
break;
}
}
});
});
});
</script>
I am trying to edit some data using boostrap and ajax, however when I run the code an error occurs.
The error is on the line
onclick="editUser('.$row->id.');"
How do I fix this?
My JavaScript code is
function edit(id) {
$.ajax({
url : "<?php echo site_url('edit')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="name"]').val(data.name);
$('[name="id"]').val(data.id);
$('[name="name"]').focus();
$('#edit').modal('show'); // show bootstrap modal when complete loaded
},
error: function (jqXHR, errorThrown)
{
alert('Error ajax');
}
});
}
My HTML code is
<?php
$no = 1;
foreach ($user as $row) {
?>
<tr>
<td><?php echo $no; ?></td>
<td><?php echo $row->nik; ?></td>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->name; ?></td>
<td align="center">
<span class="glyphicon glyphicon-pencil"></span>
</td>
<?php $no++; }?>
You have a bit of php/javascript soup. Your href value needs to be enclosed in php tags. Change:
onclick="editUser('.$row->nik.');"
to
onclick="editUser('<?php echo $row->nik;?>');"
An addition to the hairmot's answer:
You would also like to escape any characters that would interfere with the html:
onclick="editUser('<?php echo htmlspecialchars($row->nik) ?>');"
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...
I am trying to delete a record from a data-table by creating a delete button for each record. My issue with the code that the first time I click on the delete button it refreshes the page and deletes the record, the second time I click the button Ajax fires up twice and I don't get the bootstrap modal, can't delete the record. Any suggestion how to fix the Ajax firing up twice.
index.php
<body>
<div id="test1234">
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>fname</th>
<th>lname</th>
<th>email</th>
<th>username</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
// connect to mongodb
$m = new MongoClient();
$db = $m->local;
$collection = $db->user;
$results = $collection->find();
foreach($results as $res){
$fname = $res['fname'];
$lname = $res['lname'];
$email = $res['email'];
$username = $res['username'];
?>
<tr>
<td><?php echo $fname; ?></td>
<td><?php echo $lname; ?></td>
<td><?php echo $email; ?></td>
<td><?php echo $username; ?></td>
<td><i class="fa fa-trash-o"></i></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#example').DataTable();
$(document).on('click','.idname', function(){
var data = $(this).serialize();
var aa = $(this).attr('id');
alert('open modal: '+aa);
$.ajax({
type: 'POST',
url: 'modal.php',
async:false,
data: ({name:aa}),
cache: false,
success: function(data){
$('#results').html(data);
}
})
return false;
});
});
</script>
<div id="results"></div>
modal.php
<?php
$email = $_POST['name'];
?>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><?php echo $email; ?></h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<form action="deleteUser.php" id="formsubmit1" method="POST">
<input type='hidden' id="email" name="email" value=<?php echo $email ?> >
<input type="submit" id="submit" value="Submit" >
</form>
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#myModal').modal('show');
});
</script>
<script>
$(document).ready(function(){
$('#formsubmit1').on('submit',function(){
alert('opened');
//e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'deleteUser.php',
data: data,
cache: false,
success: function(data){
$('#results3333').html(data);
//alert('res2');
}
})
return false;
});
$('#formsubmit1').on('submit', function(){
//alert('close');
$('#myModal').hide();
$('.modal-backdrop').hide();
});
//refresh page
$('#formsubmit1').on('submit', function(){
alert('refresh');
//e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'index.php',
data: data,
cache: false,
success: function(data){
$('#test1234').html(data);
alert('ref2');
}
})
return false;
});
});
</script>
userDelete.php
<?php
$email = $_POST['email'];
$m = new MongoClient();
$db = $m->local;
$collection = $db->user;
$results = $collection->remove(array('email' => $email));
?>
As #Michelem has mentioned there are multiple functions attached as submit-handlers to your form with id formsubmit1 inside modal.php.
$('#formsubmit1').on('submit',function(){
alert('opened');
//e.preventDefault();
var data = $(this).serialize();
//////////////////HERE////////////////////////
$.ajax({
type: 'POST',
url: 'deleteUser.php',
data: data,
cache: false,
success: function(data){
$('#results3333').html(data);
//alert('res2');
}
})
return false;
});
$('#formsubmit1').on('submit', function(){
//alert('close');
$('#myModal').hide();
$('.modal-backdrop').hide();
});
//refresh page
$('#formsubmit1').on('submit', function(){
alert('refresh');
//e.preventDefault();
var data = $(this).serialize();
//////////////////HERE////////////////////////
$.ajax({
type: 'POST',
url: 'index.php',
data: data,
cache: false,
success: function(data){
$('#test1234').html(data);
alert('ref2');
}
})
return false;
});