Hi I'm trying to get the id for each row shown in while loop in my jquery function
Here are the request and view (PHP code)
<div class="container">
<table class="table table-striped">
<div class="table responsive">
<thead class="black white-text">
<tr>
<th>#</th>
<th>Nom et Prénoms</th>
<th>Fonction</th>
<th>Université</th>
<th>Email</th>
<th>Contact</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$result = $connection->query($stmt) ;
if($result->rowCount() > 0)
{
while($row = $result->fetch(PDO::FETCH_BOTH))
{
echo '<tr>
<td scope="row">'.$row["id"].'</td>
<td>'.$row["nom"].'</td>
<td> '.$row["fonction"].'</td>
<td> '.$row["nomU"].'</td>
<td> '.$row["email"].'</td>
<td> '.$row["Contact"].'</td>
<td>' ?>
<button type="button" class="btn btn-success valider">Valider</button> /<button type="button" class="btn btn-danger rejeter">Rejeter</button>
<?php
echo '</td>
<td>'
?>
<input type="hidden" class="the_id" value='<?php echo $row[' id ']; ?>'>
<?php echo '</td>
</tr>';
}
}
else
{
echo "0 results";
}
?>
</tbody>
</div>
</table>
</div>
And I want to show the id of each row when I click on the button "valider" for the line with jquery but it's showing the first id for all the row.
Here is th jquery code
$(document).ready(function(){
$('.valider').click(function(e){
alert($('.the_id').val());
});
});
Almost right. Remember that when accessing by a class name rather than an ID, you will get all of those objects.
So, we need to be more specific. Give this a try:
$('.valider').click(function(e){
var id = $(this).parent().parent().find('td').find('.the_id').val();
alert(id);
});
This takes you from $(this), your button, to its parent <td>, then the parent <tr>, then looks for any classes of .the_id inside the tr, in other words, the specific one you want.
I usually add a custom attribute to the elements, like data-custom-id.
'<button type="button" class="btn btn-success valider" data-custom-id="'.$row["id"].'">Valider</button>'
And then in the calling function I can access the object with this
$('.valider').click(function(e){
alert($(this).attr('data-custom-id'));
});
You need to go up to the parent tr to get the related input so you could use closest() with the $(this) :
$('.valider').click(function(e){
alert( $(this).closest('tr').find('.the_id').val() );
});
Related
I have a datatable which retrieves data from db, i want to be to implement a modal pop up under the row improvement actions so instead displaying the actual improvement actions i want like a symbol under that row so when i click it a modal appears with the improvement actions while all the other data remains the same , i want to implement this using ajax but am quite a novice in ajax please assist.
<table class="table table-hover table-striped table-bordered datatable-basic" >
<thead>
<tr>
<tr class="bg-violet-400" >
<th>ID</th>
<th>Site</th>
<th>Date</th>
<th>SN</th>
<th>Gap identified</th>
<th>Improvement Actions</th>
<th>Timeline</th>
<th>Person responsible</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$connect = mysqli_connect("localhost", "root", "", "dqa");
$query=mysqli_query($connect,"SELECT * FROM action_plan");
while($row=mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['site'] ?></td>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['sn'] ?></td>
<td><?php echo $row['gap_identified'] ?></td>
<td><?php echo $row['Improvement_Actions'] ?></td>
<td><?php echo $row['timeline'] ?></td>
<td><?php echo $row['person_responsible'] ?></td>
<td><?php if( $row['status'] == 1 )
{
echo ' <button type="button" class="btn bg-grey">Approved</button></span>';
}
elseif( $row['status'] == 0 ) {
echo ' <button type="button" class="btn btn-danger">Active Action</button></span>';
}
elseif( $row['status'] == 2 ) {
echo ' <button type="button" class="btn bg-brown"> Resubmission </button></span>';
}
elseif( $row['status'] == 3 ) {
echo ' <button type="button" class="btn bg-orange">Action Due</button></span>';
}
?></td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
Without any sample data or example data, I can only speculate at what you are trying to accomplish. Here is an example that I think you may find helpful.
$(function() {
$(".table").DataTable();
$(".table tbody .actions").button({
showLabel: false,
icon: "ui-icon-extlink"
}).click(function(e) {
var self = $(this);
var row = $(this).attr("href").substring(1);
var siteurl = "<?php echo siteurl('improvement');?>";
var form = $("<form>", {
id: "form-" + row
});
form.append($("<input>", {
type: "hidden",
name: "rowid",
value: row
}));
var dialog = $("<div>", {
title: "Improvement Actions - Row " + row
}).append(form).dialog({
modal: true,
create: function(e, ui) {
$.getJSON(siteurl + "/" + row, function(data) {
$('[name="rowid"]', this).val(data.id);
});
},
close: function(e, ui) {
self.data("results", form.serialize());
dialog.dialog("destroy").remove();
}
});
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<table class="table table-hover table-striped table-bordered datatable-basic">
<thead>
<tr>
<tr class="bg-violet-400">
<th>ID</th>
<th>Site</th>
<th>Date</th>
<th>SN</th>
<th>Gap identified</th>
<th>Improvement Actions</th>
<th>Timeline</th>
<th>Person responsible</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td>
LOC-1
</td>
<td>
04/24/2018
</td>
<td>
1001
</td>
<td>
0.1
</td>
<td>
Improvement Actions
</td>
<td>
</td>
<td>
John Smith
</td>
<td>
<button type="button" class="btn bg-grey">Approved</button>
</td>
</tr>
</tbody>
</table>
Assuming you are using DataTable, The table is populated with various data from PHP, resulting in HTML like shown above. You can then use jQuery UI to program the button to build a dialog. One of the callback events for .dialog() is create, see more: http://api.jqueryui.com/dialog/#event-create
You can perform your AJAX call at this time to get specific data for this dialog. In my example, all of it is being created dynamically, so there is no need to reset forms etc.
I advise using $.getJSON(), but there is nothing wrong with the $.ajax() code you implemented. The $.getJSON() simply assumes you are performing a GET call to a resource that will return JSON data. Resulting in simplified code.
Testing of this example is not complete as the PHP Script URL is fake or will be null.
Hope that helps.
I have some problem when I trying to delete data using form with post method, I did this because many people said using $_GET method is not safe enough. So I try using this method,
I load the data from load.php
<?php
session_start();
require_once('../../classes/Config.php');
require_once('../../classes/Database.php');
require_once('../../classes/Query.php');
require_once '../../classes/ErrorHandler.php';
require_once '../../classes/Validator.php';
require_once '../../classes/Token.php';
$connection = new Database($host, $username, $password, $database);
$main = new Query($connection);
$table = 'karyawan';
$selectData = $main->select($table);
while($fetchData = $selectData->fetch_object()){
$delete = '<form action="" method="post"><input type="hidden" name="id_karyawan" value="'.$fetchData->id_karyawan.'"><input type="hidden" name="token" value="'.$_SESSION['token'].'"><a><button type="submit" class="btn btn-danger btn-xs" id="delete" onclick="deleteData()">delete</button></a></form>';
$button = '<td class="text-center">'.$delete.'</td>';
echo '<tr>
<td class="text-center">'.$fetchData->id_karyawan.'</td>
<td class="text-center">'.$fetchData->nama_karyawan.'</td>
<td class="text-center">'.$fetchData->alamat_karyawan.'</td>
<td class="text-center">'.$fetchData->telepon_karyawan.'</td>
<td class="text-center">'.$fetchData->akses.'</td>
'.$button.'
</tr>';
}
in $delete I set a form with POST method, so I have some forms to delete these datas, here is where my load.php should be loaded,
<div class="table-responsive">
<table class="table table-hover table-bordered table-condensed bg-success">
<thead>
<th class="text-center">ID Karyawan</th>
<th class="text-center">Nama Karyawan</th>
<th class="text-center">Alamat Karyawan</th>
<th class="text-center">Telepon Karyawan</th>
<th class="text-center">Hak Akses</th>
<th class="text-center">Opsi</th>
</thead>
<tbody id="load-data">
</tbody>
<tr>
<td colspan="5"></td>
<td class="text-center"><button class="btn btn-info btn-xs" id="showTambah">Tambah</button></td>
</tr>
</table>
<script type="text/javascript" src="karyawan.js"></script>
and here is my jQuery scripts
load();
deleteData();
function load() {
$('#load-data').load('process/karyawan/load.php');
}
function deleteData(){
$('#delete').click(function(e){
e.preventDefault();
alert('testing');
});
}
when I click delete button function deleteData() didn't work well both of preventDefault() or alert() message.
Can someone give me some advices??
Remove deleteData() from submit button and add class called btn-delete on the button and remove $('#delete').click(function(e){}); event and use $('.btn-delete').on("click",function(e){}); this event. As your content loadind dynamically click event will not work you have to use below code.
$('.btn-delete').on("click",function(e){
e.preventDefault();
alert("test")
});
I have a table like this:
When I click the Delete! button, I want to pass the role ID to the controller.
After looking for a lot of cases in stackoverflow. I've just succeeded to retrieve the role ID using JS.
Code like this:
$(".deleteButton").click(function() {
var $row = $(this).closest("tr");
var $text = $row.find("td:first-child").text();
// Let's test it out
alert($text);
});
But the problem is, I don't how to pass it back to the button, so then the button can pass it to the controller.
Is there any simple way to pass it to the controller? Maybe without retrieving the role ID first, and when click the button the value passed and the controller called at once?
This is my code:
<table class="table" id="myTable">
<thead class="text-primary">
<th class="col-md-1">ID Role</th>
<th class="col-md-3">Role</th>
<th class="col-md-3">Jumlah Member</th>
<th></th>
</thead>
<tbody>
<?php
foreach($result as $row) { ?>
<tr>
<td><?php echo $row->id_role ?></td>
<td><?php echo $row->role ?></td>
<td><?php echo $row->jumlah ?></td>
<td>
<button type="button" class="btn btn-success btn-sm editButton">Edit!</button>
<button type="button" class="btn btn-danger btn-sm deleteButton">Delete!</button>
</td>
</tr>
<?php
} ?>
</tbody>
</table>
Do you have to use JavaScript? If not, this is a simple task for a form
<form action="path/to/your/controller" method="post">
<table class="table" id="myTable">
<!-- thead, etc -->
<tbody>
foreach($result as $row) : ?>
<tr>
<td><?= $row->id_role ?></td>
<td><?= $row->role ?></td>
<td><?= $row->jumlah ?></td>
<td>
<button type="submit" name="edit" value="<?= htmlspecialchars($role->id_role) ?>"
class="btn btn-success btn-sm editButton">Edit!</button>
<button type="submit" name="delete" value="<?= htmlspecialchars($role->id_role) ?>"
class="btn btn-danger btn-sm deleteButton">Delete!</button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</form>
Your controller would then receive either $_POST['edit'] or $_POST['delete'] with the role ID as the value.
If you're interested in securing your form from possible cross-site-request-forgery attacks, CodeIgniter has a built-in solution.
Otherwise, I would just add the id_role property to the button, eg
<button type="button" class="btn btn-danger btn-sm deleteButton" value="<?= htmlspecialchars($role->id_role) ?>">Delete!</button>
and in your JS
$('.deleteButton').on('click', function(e) {
var roleId = this.value
$.ajax({
url: '/roles/' + roleId, // assuming a REST API
method: 'DELETE'
}).done(function() {
alert('Deleted role ' + roleId);
})
})
You assign the role id to another <td> which is a little bit longer to get the id by jQuery. You easily get the click button id just give to an id like.
<button type="button" id="<?php echo $row->id_role ?>" class="btn btn-danger btn-sm deleteButton">Delete!</button>
and then you can easily get the specific row id
$(".deleteButton").click(function() {
var $text= $(this).attr("id");
alert($text);
});
and then you can send that id to controller by ajax.
This is my controller, that i use to send the row to the model:
function excluir(){
$codcliente = $this->input->post('codcliente');
$this->load->model("Cliente_class");
$this->Cliente_class->excluirCliente($codcliente);
redirect('cliente/busca');
}
my model:
function excluirCliente($codcliente){
$this->db->delete('cliente', array('codcliente' => $codcliente));
}
my table (view):
<form action="#" method="POST" id="form">
<div style="float: left;">
<input type="button" onclick="cadastro();" value="Novo cliente" name="botao" class="btn btn-primary">
</div>
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
<th>Cidade</th>
<th>Telefone</th>
<th> </th>
</tr>
<tbody>
<?php
foreach ($records as $row){ ?>
<tr>
<td><input name="codcliente" id="codcliente" value="<?php echo $row->codcliente ?>"></td>
<td><?php echo $row->nome ?></td>
<td><?php echo $row->cidade ?></td>
<td><?php echo ($row->telefone == null) ? "-" : $row->telefone ?></td>
<td><center><input type="button" onclick="excluir();" value="Delete"></td>
</tr>
<?php } ?>
</tbody>
</form>
</thead>
</table>
and my JS:
function excluir(){
document.forms['form'].action = "<?php base_url();?>excluir";
document.forms['form'].submit();
}
its working fine, but the code is deleting my last row in relation with the table on html. i used the order by too see whats beeing deleted, and it works the same...
i dont know what's wrong
Your problem is that you are using the same form name name="codcliente" for all your rows and then submitting the whole form when you delete. The server sees the last value for codcliente which will be your last row and hence deletes it.
To fix, I suggest you use unique form names for each row for all your row fields. Eg. Instead of name="codcliente" use name="codcliente_<?php echo $row->id ?>". And then when you post to the server to delete, use a data-name=<?php echo $row->codcliente ?> on the delete button and in the onClick handler use $(this).data('name') to get the unique name of the field and post that to the server. I suggest you use ids instead of names as well.
Based on the question asked here: https://www.quora.com/How-do-I-display-a-div-table-when-a-link-is-clicked
I used the code given by the top answer.
Now, my code is modified to use variables:
echo ''.$row['Name'] .'';
It's in a while loop.
<div id="data-table" style="visibility: hidden;">
<table>
<?php
if $Name ==
?>
</table>
</div>
My div is supposed to show the data for the item whose Name is selected. eg: if "Robin" is selected, Robin's data will be shown. so how do I get the div to check which Name/link was clicked and then show the data for that Name/link?
Your question is a little hard to follow. Hopefully this can clear up some of your front-end issues.
HTML:
<div class="container">
<h3>Triggers</h3>
<p class='table-reference' data-record-ref='1'>Highlight Row #1</p>
<p class='table-reference' data-record-ref='2'>Highlight Row #2</p>
<p class='table-reference' data-record-ref='3'>Highlight Row #3</p>
<hr>
<h3>Table</h3>
<table id="record-table">
<thead>
<tr>
<th>ID</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr data-record='1'>
<td>#1</td>
<td>Record</td>
</tr>
<tr data-record='2'>
<td>#2</td>
<td>Record</td>
</tr>
<tr data-record='3'>
<td>#3</td>
<td>Record</td>
</tr>
</tbody>
</table>
</div>
Javascript/jQuery:
(function($) {
$(function() {
$("*[data-record-ref]").click(function() {
var id = $(this).data("record-ref");
var element = $("*[data-record='"+id+"']");
if(!!element) {
$(this).toggleClass("highlight");
element.toggleClass("highlight");
} else {
console.error("Record Not Find.");
}
});
});
}) ($);
Demo