How to display data in its row table? - php

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})
}
}
})

Related

Change specific dynamically created table row html and text from ajax response

From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>

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

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"

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>

Show the elements of a specific table row when button is clicked inside that table row

I have a database with folder paths in index.php. The user then selects one or more paths to run which are then queried to search.php. Each row has its respected button, when the button is clicked the path gets send to a series of functions (ajax.php, ajax2.php, ajax3.php) and at the end a report is saved in a folder. pdf_report.php should then display the report inside the row.
My issue is when any button is clicked, the report always shows up in the first row and not in the row clicked on. The following is my code:
search.php
<?php
...
while($row = $result->fetch_assoc()){
$field1name = $row["test_id"];
$field2name = $row["path"];
$field3name = $row["video1_path"];
$field4name = $row["video2_path"];
$field5name = $row["video3_path"];
$field6name = $row["video4_path"];
echo "<tr>
<td> ".$field1name." </td>
<td> ".$field2name." </td>
<td> ".$field3name." </td>
<td> ".$field4name." </td>
<td> ".$field5name." </td>
<td> ".$field6name." </td>
<td><div>
<button class='edit' id='" . $row['test_id'] . "'>Run</button>
</div></td>
<td><div id='result'>
<p></p>
</div></td>
</tr>";
}
}else {
echo '<span style="color:#ff0000;text-align:center;">No Test ID Selected!</span>';
}
}
// Close connection
mysqli_close($conn);
?>
</table>
</div><br>
<div style="overflow-x:auto;">
<table id=test_data>
<tr>
<th>Progress</th>
<th>Progress Status</th>
</tr>
<tr>
<td><div><progress id='progBar' value='0' max='100'></progress></div></td>
<td><div><p id='progress-text'></p></div></td>
</tr>
</table>
</div>
<!--Uses jquery to run 3 scripts and displays it in a progress bar-->
<script>
$(document).on('click', '.edit', function(){
//set cookie value to 'path'
var fcookie='mycookie';
var test_id = $(this).attr('id');
if(test_id) {
var path = $(this).closest('tr').find("td:nth-child(2)").text()};
document.cookie='fcookie='+path;
//Start of 1st script
$.ajax({
url: "ajax.php",
type:"POST",
success: function(data) {
//alert("File 1 Completed")
$("#progress-text").text("Executing file 1");
$('#progBar').val(25);
//Start of 2nd script
$.ajax({
url: "ajax2.php",
type:"POST",
success: function(data2) {
//alert("File 2 Completed")
$("#progress-text").text("Executing file 2");
$('#progBar').val(50);
//Start of 3rd script
$.ajax({
url: "ajax3.php",
type:"POST",
success: function(data2) {
//alert("File 2 Completed")
$("#progress-text").text("Complete");
$('#progBar').val(100);
//Loads the report
$("#result").load("pdf_report.php");
}
})
}
})
}
})
return false;
//});
});
</script>
I am new to php and jquery. Thanks in advance
You can try to change:
//Loads the report
$("#result").load("pdf_report.php");
By:
//Loads the report
$(this).closest('tr').find("td:nth-child(8) div").load("pdf_report.php");

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();
}

Categories