After ajax success show child table in if condition in ajax success - php

This is an HTML table with all buttons
On click of a button in table row button, status has to be updated in backend PHP and in ajax success I have to display child table
<table id="example" class="stripe row-border order-column" width="100%">
<thead>
<tr>
<th>Drawing</th>
<th style="display:none">Overview</th>
<th>Stage</th>
<th>Status</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><button type="button" class="button clarify" >Clarify</button></td>
<td><button type="button" class="button allot">Allott</button></td>
<td><button type="button" class="button start">Started/Pused</button></td>
<td><button type="button" class="button correctit">Quality Checking</button><td>
<td><button type="button" class="button send">Send</button></td>
</tr>
<tr id="2">
<td><button type="button" class="button clarify" >Clarify</button></td>
<td><button type="button" class="button allot">Allott</button></td>
<td><button type="button" class="button start">Started/Pused</button></td>
<td><button type="button" class="button correctit">Quality Checking</button><td>
<td><button type="button" class="button send">Send</button></td>
</tr>
</tbody>
</table>
here is the ajax call each click on the button status has to update and if the button status or data is == 2 then I want to display the child table
$(".button").click(function() {
$this = $(this);
//alert("am button");
var drawingid = $(this).closest('tr').attr('id'); // table row ID
var stage_id = $(this).closest('tr').find('.button').val();
// alert(stage_id);
$.ajax({
type: "POST",
url: "stage2.php",
dataType: "json",
data: {
"drawingID": drawingid,
"stage_ID": stage_id
},
success: function(data) {
alert(data);
if ( data == 2) {
**//here if the data is == 2 then show child table with dropdown** $this.parent().parent().find('.button').val(data);
$this.parent().parent().find('.button').html('Allott').addClass('allot').removeClass('clarify');
var tr = $(this).closest('tr');
id = $(this).closest('table').attr('id');
table = $('#' + id).DataTable();
var row = table.row(tr);
// Open this row
row.child(format(row.data(), id)).show();
tr.addClass('shown');
}
}
});
});

pass 0/1 an additinal value in ajax, and run statement/function by using an "if"

Related

How to display data in its row table?

let's say I have 5 rows of data, is there a way where I can display the data on its row? how?
in my code, when I hit the button on row 5 the result displays in data column.
<table>
<th>action</th><th>data</th>
<tr>
<td>
<button class="getdata" type="button" data-id="1">
</td>
<td>
<i class="data"></i>
</td>
</tr>
<tr>
<td>
<button class="getdata" type="button" data-id="2">
</td>
<td>
<i class="data"></i>
</td>
</tr>
<tr>
<td>
<button class="getdata" type="button" data-id="3">
</td>
<td>
<i class="data"></i>
</td>
</tr>....
</table>
$('.getdata').click(function(){
var id = $(this).attr('data-id');
$.ajax({
url: 'log.php',
method: 'GET',
data:{id:id},
success:function(){
$('.data').html(id)
}
})
})
In your AJAX success / done handler, traverse up from the current button to a sensible parent (<tr>) then down to the .data element
$('.getdata[data-id]').on("click", function() {
const btn = $(this)
$.get("log.php", { id: btn.data("id") }).done(data => {
btn.closest("tr").find(".data").html(id) // or data ¯\_(ツ)_/¯
})
})
See .closest()
Did you know, you might not need jQuery
// using event delegation at the <table> level
document.querySelector("table").addEventListener("click", async e => {
const btn = e.target.closest("button.getdata[data-id]")
if (btn) { // the click came from a button
const id = btn.dataset.id
const params = new URLSearchParams({ id })
const res = await fetch(`log.php?${params}`)
const data = await res.text()
if (res.ok) {
btn.closest("tr").querySelector(".data").innerHTML = id // or data
} else {
console.error(res.status, data})
}
}
})

status update on nested statement partially working

Please I need help to figure out why my code below isn't working. I'm not very good at PHP and ajax to start with but find it difficult to figure out why the code below wouldn't function properly.
What it does: changes data in database to 'Disable' but to update to 'Enable' on-click wouldn't work. Please help!
status.php
<?php
session_start();
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="User"){
header('location:index.php');
}
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
if (isset($_POST['ridd'])){
$id=$_POST['ridd'];
if($row->user_status == 'Enable'){
$status_str="Disable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str, $id]);
}else if($row->user_status == 'Disable'){
$status_str2="Enable";
$sql="UPDATE `tbl_user` SET `user_status` = ? WHERE userid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$status_str2, $id]);
}else{
echo'Internal loop error in Updating';
}
}
}
registration.php
<script>
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id
},
success: function(data) {
//tdh.parents('tr').load;
}
});
swal("User status has been changed!", {icon: "success",});
window.location.reload(true);
} else {
swal("No action performed!");
window.location.reload(true);
}
});
});
});
</script>
here is my table code in registration.php
<tbody>
<?php
$select=$pdo->prepare("select * from tbl_user order by userid desc");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ) ){
$status='Disable';
$colour="btn-danger";
if($row->user_status == 'Enable'){
$status='Enable';
$colour="btn-success";
}
echo'
<tr>
<td>'.$row->userid.'</td>
<td>'.$row->username.'</td>
<td>'.$row->user_status.'</td>
<td>
<div id='.$row->userid.' class="switch">
<button type="button" class="btn '.$colour.'">'.$status.'</button>
</div>
</td>
<td>
<button id='.$row->userid.' class="btn btn-danger btndelete" ><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
';
}
?>
</tbody>
When I click on button 'switch', I'm able to perform a toggle function so that it can update either 'Enable' or 'Disable' on my database. At the moment, only the disable is working and I have to manually enable the user from the database (phpmyadmin).
You can check if the button which is clicked has class btn-success if yes then now we need disable it or else enable so send this as well in your ajax call and at your backend get it using $_POST["status"] and update same . Also, you don't need to reload page instead inside your success function of ajax just change the button using .html().
Demo code :
$(document).ready(function() {
$('.switch').click(function() {
var tdh = $(this);
var id = $(this).attr("id");
swal({
title: "Do you want to Change user status?",
text: "Once changed, it can be reversed!",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
var button_status = $(this).find("button").hasClass("btn-success") ? "Disable" : "Enable"; //check if button has success means we need disable it now else enable .
/*$.ajax({
url: 'status.php',
type: 'POST',
data: {
ridd: id,
status: button_status //send to chnage
},
success: function(data) {*/
//if disable
if (button_status == "Disable") {
$("#" + id).html("<button type='button' class='btn btn-danger '>Disable</button>") //put enable button
tdh.closest("tr").find("td:eq(2)").text("Disable")
} else {
$("#" + id).html("<button type='button' class='btn btn-success '>Enable</button>") //disable buttn
tdh.closest("tr").find("td:eq(2)").text("Enable")
}
/* }
});*/
swal("User status has been changed!", {
icon: "success",
});
} else {
swal("No action performed!");
}
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
<table class="table">
<tbody>
<tr>
<td>1</td>
<td>sw</td>
<td>Enable</td>
<td>
<div id='1' class="switch">
<button type="button" class="btn btn-success ">Enable</button>
</div>
</td>
<td>
<button id='1' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
<tr>
<td>2</td>
<td>sw</td>
<td>Disable</td>
<td>
<div id='2' class="switch">
<button type="button" class="btn btn-danger ">Disable</button>
</div>
</td>
<td>
<button id='2' class="btn btn-danger btndelete"><span class="glyphicon glyphicon-trash" style="color:#ffffff" data-toggle="tooltip" title="Delete User"></span></button>
</td>
</tr>
</tbody>
</table>

Laravel: Jquery on click function issue

I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});
You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});
Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}

Delete a table row is not working with jquery on button click

I have problem when I click on button the table row is not deleted tr id and button id are both same value. please tell where I am doing wrong
<tr id="<?php echo $result->id;?>">
<td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
<td><button type="button" name="remove" id="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
</tr>
Jquery code
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).attr("id");
$('#' + btn_id + '').remove();
});
});
Thanks in advance
id need to be unique per element if you are going to use them in jQuery, and hense your code is not working (As tr and td sharing same value for id).
Simplify you code through closest()
$(document).ready(function(){
$('.button_remove').click(function(){
$(this).closest('tr').remove();
});
});
Note:- Remove id from tr and td both. As it's not needed at all. It will make your HTML structure correct and cleaner.
Thats because you are using same id for tr and button....Try to use data-attributes here
<tr id="<?php echo $result->id;?>">
<td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
<td><button type="button" name="remove" data-row="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
<tr>
And then use jQuery like this
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).data("row");
$('#' + btn_id + '').remove();
});
});
$(document).ready(function() {
$('.button_remove').click(function() {
$(this).parents().eq(1).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" value="1"/></td>
<td><button type="button" class="button_remove">X</button></td>
</tr>
<tr>
<td><input type="text" value="2"/></td>
<td><button type="button" class="button_remove">X</button></td>
</tr>
</table>

jquery button click event isn't working on dataTable

After adding any row in dataTable, edit or delete button click isn't working. I have done this with ajax. in success function i have destroyed the dataTable. Then load all the data and initiate the dataTable. My codes are following.
HTML Code:
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<button class="btn btn-success" title="Add Items" id="addCalzone"><i class="halflings-icon white plus"></i> Add Item</button><br/><br/>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Price</th>
<th>
<div class="text-center">
Action
</div>
</th>
</tr>
</thead>
<tbody class="dataTable-tbody">
<?php foreach($row as $key => $r): ?>
<tr class="tableRow" data-id="<?= htmlentities(stripcslashes($r['id']), ENT_QUOTES, 'UTF-8'); ?>">
<td></td>
<td><?= htmlentities(stripcslashes($r['name']), ENT_QUOTES, 'UTF-8'); ?></td>
<td> $ <?= htmlentities(stripcslashes($r['price']), ENT_QUOTES, 'UTF-8'); ?></td>
<td>
<div class="text-center">
<button class="btn btn-info editCalzone" title="Edit"><i class="halflings-icon white edit"></i> Edit</button>
<button class="btn btn-danger dltCalzone" title="Delete"><i class="halflings-icon white trash"></i> Delete</button>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="modal hide fade" id="addItem">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1>Calzone</h1>
</div>
<div class="modal-body">
<h3>Name</h3>
<input type="text" id="itemName" value="" required="required" />
<input type="hidden" id="type" value="add"/>
<h3>Price</h3>
<input type="number" min="0" step="0.01" value="" required="required" id="itemPrice" />
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="addClose" data-dismiss="modal">Close</button>
<button class="btn btn-success" id="addbtn">Save</button>
</div>
</div>
Javascript Code:
function initDataTable(){
$('.datatable').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span12'i><'span12 center'p>>",
"sPaginationType": "bootstrap",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
} );
$('.btn-close').click(function(e){
e.preventDefault();
$(this).parent().parent().parent().fadeOut();
});
$('.btn-minimize').click(function(e){
e.preventDefault();
var $target = $(this).parent().parent().next('.box-content');
if($target.is(':visible')) $('i',$(this)).removeClass('chevron-up').addClass('chevron-down');
else $('i',$(this)).removeClass('chevron-down').addClass('chevron-up');
$target.slideToggle();
});
$('.btn-setting').click(function(e){
e.preventDefault();
$('#myModal').modal('show');
});
}
$('#addbtn').click(function(){
var $add = {
name : $('#itemName').val(),
cost : $('#itemPrice').val(),
type : $('#type').val()
};
if($add.name == '' || $add.cost == ''){
alert('Both fields must be filled');
}else{
$.ajax({
type: 'POST',
dataType: 'json',
url: $calzone.submitURL,
data: {
calzoneName: $add.name,
calzoneCost: $add.cost,
calzoneAction: $add.type
},
cache: false,
error: function(){
alert('An Error Occured !!');
},
success: function(response){
alert('Successfully Saved !!');
$('#itemName').val('');
$('#itemPrice').val('');
$('#type').val('');
$('.datatable').DataTable().destroy();
$('.dataTable-tbody').html('');
for(i=0; i<response.length; ++i){
var content = '<tr class="tableRow" data-id="' + response[i].id + '">' +
'<td>' + (i+1) + '</td>' +
'<td>' + response[i].name + '</td>' +
'<td>' + response[i].price + '</td>' +
'<td>' +
'<div class="text-center">' +
'<button class="btn btn-info editCalzone" title="Edit"><i class="halflings-icon white edit"></i> Edit</button> ' +
'<button class="btn btn-danger dltCalzone" title="Delete"><i class="halflings-icon white trash"></i> Delete</button>' +
'</div>' +
'</td>' +
'</tr>';
$('.dataTable-tbody').append(content);
}
initDataTable();
$('#addItem').modal('hide');
}
});
}
});
$('.editCalzone').click(function(){
$('#addItem').modal('show', {
backdrop: 'static'
});
var $edit = {
name : $(this).closest('tr').find('td').eq(1).text(),
price : $(this).closest('tr').find('td').eq(2).text().split(' ')[2],
type : $(this).closest('tr').data('id')
};
$('#itemName').val($edit.name);
$('#itemPrice').val($edit.price);
$('#type').val($edit.type);
});
$('.dltCalzone').click(function(){
var $dlt = {
confirm : confirm("Are you want to delete the selected item ?"),
key : $(this).closest('tr').data('id')
};
if($dlt.confirm){
$.ajax({
type: 'POST',
url: $calzone.submitURL,
data: {
deleteKey : $dlt.key
},
error: function(){
alert('An Error Occured');
},
success: function(){
alert('Data has been deleted !!');
location.reload();
}
});
}else{
alert('Your data is safe !');
}
});
The response from the server is perfect. There is no error. But after adding a row or editing a row's information, Edit and Delete button isn't working. But It's working after reload the page. What is the problem in the dataTable initialization, i can't figure out. Please help me to figure out the problem and solve it.
replace your
$('.editCalzone').click(function(){
$('.dltCalzone').click(function(){
with
$(document).on('click', '.editCalzone', function(){
$(document).on('click', '.dltCalzone', function(){

Categories