I have a table with the following PHP code:
<table id="myTable">
<tr class="header">
<th>Naam</th>
<th>Bedrijf</th>
</tr>
<?php
include 'assets/scripts/connect.php';
$q = mysql_query("SELECT * FROM `users` WHERE `admin`='0' AND `deleted`='0'");
while ($row = mysql_fetch_assoc($q)) {
$id = $row['id'];
?>
<tr class="trash" onclick="deletePopUp()" data-id="<?php echo $id; ?>">
<td><?php echo $row['fname']; ?> <?php echo $row['lname']; ?></td>
<td><?php echo $row['company']; ?></td>
</tr>
<?php
}
?>
</table>
As you can see, I add a data-id for each row that is created by the code in conjunction with the database. The onClick function makes a modal pop up with the request to confirm whether the user really wants to delete this customer. The modal is coded the following way:
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-top">
<h1>Weet je het zeker?</h1>
<span class="close">×</span>
</div>
<div class="modal-inner">
Verwijderen
Annuleren
</div>
</div>
</div>
The two anchor tags are for the confirmation. So one sould go to the external PHP script to delete the customer according to their ID. I use the GET method for this. But the link on the modal now forms always with the same ID. Do the link is always:
/assets/scripts/delete-user.php?id=2
I would like to have the ID being the same as that of the customer clicked on.
I tried using jQuery to form this link, but I get the same result. This is the jQuery I used:
var id=$('.trash').data('id');
$('#delete').attr('href','/assets/scripts/delete-user.php?id='+id);
But as said, this gives the same result.
How can I get the link on the modal to have a dynamic ID?
Because you added an inline js event handler function I would suggest to use the parameters:
event: the event object
this: the current element
In your case your may write:
<tr class="trash" onclick="deletePopUp(event, this)" data-id="This is An ID">
Therefore, your deletePopUp function will be:
function deletePopUp(e, ele) {
var id = ele.dataset['id']; // get current data-id
$('#delete').attr('href','/assets/scripts/delete-user.php?id='+id);
$('#myModal').modal('show');
}
The snippet:
function deletePopUp(e, ele) {
var id = ele.dataset['id'];
$('#delete').attr('href','/assets/scripts/delete-user.php?id='+id);
$('#myModal').modal('show');
}
$('#delete').on('click', function(e) {
e.preventDefault();
console.log(this.href);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="myTable">
<tr class="header">
<th>Naam</th>
<th>Bedrijf</th>
</tr>
<tr class="trash" onclick="deletePopUp(event, this)" data-id="This is An ID">
<td>name</td>
<td>company</td>
</tr>
</table>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-top">
<h1>Weet je het zeker?</h1>
<span class="close">×</span>
</div>
<div class="modal-inner">
Verwijderen
Annuleren
</div>
</div>
</div>
A simpler method to above could be:
(I haven't tested this, I assume this does what you need)
$(document).ready(function() {
$(".trash").click(function() {
var id = $(this).attr("data-id");
$("#delete").attr("href","delete-user.php?id="+id);
});
});
Related
so im working on this library project where students can order books and admin has to confirm those requests from his side.
here is a pic of the project to have a small idea:
those are students requests
when u click on the blue button you can see more details of the student order:order details
as you can see there is the book that the student has ordered.
now what i wanted is to refresh just the modal after the admin click accept and i did achieve that by using the .load() function here is the piece of code that responsible that :code that load the modal
since we have multiple students and they can order multiple books so i had to use 2 loops that why you see those dynamic id on the modal id and button id, $tmp is for the students loop and $tmp2 is for the books loop. so far so good, the problem is when the modal refresh i lose my script tag which is bad why because all my buttons have click events so no script means buttons will not work here is before and after modal refresh before refresh you can see the script tag that responsible for the buttons and the ajax call here is after as you can see the modal refresh successfully but i lost my script so the buttons will not work so i have to reload the whole page so i can retrieve my script then the buttons will work again.
some of the solutions i tried is to put the script outside of the modal because i assumed .load() can only fetch html no script but i can't because i need the script to be inside that loop in the modal for the books button
here is the modal code if you want more details :
<!-- user books details modal -->
<div class="modal fade" id="userBooksDetails<?= $tmp ?>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg ">
<div id="modalContent<?= $tmp ?>" class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
</div>
<div id="modalBody<?= $tmp ?>" class="modal-body">
<table class="table">
<thead>
<tr>
<th scope="col">Picture</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<?php
//dont mind this its just to fetch information of the book to display it in the modal
$livre = new Livre();
$exemplaire = $livre->myBooks($user->id);
if ($exemplaire) {
//here is the second loop because student can order multiple books and each book request need to have an unique id for it button
foreach ($exemplaire as $exem) {
$tmp2--;
$copy = Exemplaire::find($exem['Num_Exemp']);
$book = Livre::find($copy->ISBN);
?>
<script>
$(document).ready(function() {
//request for accepting the order of the user
$("#acceptBook<?= $tmp2 ?>").click(function() {
let copyId = $(this).attr("data-idCopy");
$.ajax({
url: "<?= PROOT ?>emprunts/acceptOrder/" + copyId,
type: "POST",
success: function(data) {
$("#modalContent<?= $tmp ?>").load(window.location.href + " #modalContent<?= $tmp ?>" );
console.log(data)
}
});
});
//request for rejecting the order of the user
$("#rejectBook<?= $tmp2 ?>").click(function() {
let copyId = $(this).attr("data-idCopy");
$.ajax({
url: "<?= PROOT ?>emprunts/rejectOrder/" + copyId,
type: "POST",
success: function(data) {
//$("#userBooksDetails<?= $tmp ?>").load(" #userBooksDetails<?= $tmp ?>");
console.log(data);
$("#modalBody<?= $tmp ?>").load(window.location.href + " #modalBody<?= $tmp ?>" );
}
});
});
//request for returning the book (is not working after reloading on accept fix it )
$("#return<?= $tmp2 ?>").click(function() {
let copyId = $(this).attr("data-idCopy");
$.ajax({
url: "<?= PROOT ?>emprunts/returnBook/" + copyId,
type: "POST",
success: function(data) {
console.log(data);
$("#modalBody<?= $tmp ?>").load(window.location.href + " #modalBody<?= $tmp ?>" );
}
});
})
})
</script>
<tr>
<th> <img src="<?= PROOT . "/public/img/books/" . $book->img ?>" class="w-50 rounded-t-5 rounded-tr-md-0 rounded-bl-md-5" aria-controls="#picker-editor">
</th>
<td class="display-6 text-align-center">
<div class="my-5">
<?= $book->Titre_livre ?>
</div>
</td>
<td>
<div class="form-group mt-4">
<button id="stat<?= $tmp2 ?>" disabled class="btn mt-5"><?php if($exem['isConfirm']==0)
echo "Not Confirmed";
else echo "Confirmed"; ?></button>
</div>
</td>
<td id="test<?= $tmp2 ?>">
<!-- here im checking if the book is confirmed if yes im showing some specific buttons if not hiding some buttons -->
<div class="form-group mt-5">
<a <?php if($exem['isConfirm']==1)
echo "hidden";
else
echo "" ?>
id="acceptBook<?= $tmp2 ?>" class="btn m-2" data-idCopy="<?= $exem['Num_Exemp'] ?>" role="button">Accept</a>
<a <?php if($exem['isConfirm']==1)
echo "hidden";
else
echo "" ?> id="rejectBook<?= $tmp2 ?>" class="btn btn-dark m-2" data-idCopy="<?= $exem['Num_Exemp'] ?>" role="button">Reject</a>
<a <?php if($exem['isConfirm']==0)
echo "hidden";
else
echo "" ?> id="return<?= $tmp2?>" data-idCopy="<?= $exem['Num_Exemp'] ?>" class="btn btn-secondary mt-4"> Return </a>
</div>
</td>
</tr>
<?php }
}
?>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
When using a <p> my script works. When I replace this with a table, it doesn't want to follow the rules of my script. The table is supposed to drop down under a button when clicked.
Im using php to get information from the database, but this shouldnt interfere as the data shows correctly in the table. I have tried to put the table in the div. I have tried different kind of style.height/style.display in the javascript.
this works properly
<h1 type="button" class="stelling">Where the sun?
</h1>
</div>
<div id="p1" class="data">
Here comes the sun!
</div>
but when I try to put a table in
<div class="stellingen";>
<div type="button" id="btn1" class="stelling-wrapper">
<img src="images/button.svg" alt="Show more..." class="btn" id="bton">
<p type="button" class="stelling">
</div>
<?php
$sql2="SELECT * FROM stellingen WHERE stelling_ID=1;";
$records2 = mysqli_query($con, $sql2);
$recordscheck2 = mysqli_num_rows($records2);
if ($recordscheck2 > 0){
while ($stellingen = mysqli_fetch_assoc($records2)){
echo "<p>".#$stellingen['Stelling']."</p>";
}
}
?>
Here is where I use the same id, just like the example that worked, i also tried with table id=p1
<div id="p1">
<table id="tabel" class="data">
<tr>
<th>Title</th>
<th>Source</th>
<th>Weight</th>
<th>Date</th>
</tr>
<?php
$sql1="SELECT * FROM stelling WHERE stelling_iD=1;";
$records1 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records1);
if ($recordscheck > 0){
while ($stelling = mysqli_fetch_assoc($records1)){
echo "<tr>";
echo "<td>".#$stelling['Title']."</td>";
echo "<td>".#$stelling['Source']."</td>";
echo "<td>".#$stelling['Wheight']."</td>";
echo "<td>".#$stelling['Date']."</td>";
echo "</tr>";
}
}
?>
</table>
</div>
</div>
</div>
The javascript
<script>
window.onload = function() {
var a = false;
document.getElementById('btn1').onclick = function (){
if(a== false){
document.getElementById('p1').style.height = "auto";
a =true;
}else{
document.getElementById('p1').style.height = "0px";
a =false;
}
}
}
</script>
I expect a div wit my table to drop down when clicked on the button
I'm working with codeigniter, and i want to show the detail data in modal, the detail data is from another table.
I have a button like this:
<button class="btn btn-info" onclick="detail_barang("<?php echo $tbrang->id_barang;?>")">Detail</button>
And this is my detail_barang function:
function detail_barang(id)
{
$('#form')[0].reset(); // reset form on modals
$.ajax({
url : "<?php echo site_url('admin/Barang/barang/ajax_detail_barang/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#modal_detail').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Detail Barang'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Kesalahan!');
}
});
}
Modal Script:
<div class="modal fade" id="modal_detail">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Detail Barang</h3>
</div>
<div class="modal-body">
<table class="table table-striped" id="tblGrid">
<thead id="tblHead">
<tr>
<th>ID Barang</th>
<th>No Inv</th>
<th class="text-right">Kondisi</th>
</tr>
</thead>
<tbody>
<?php
foreach($detail_barang as $detil)
{?>
<tr>
<td><?php echo $detil->id_barang ?></td>
<td><?php echo $detil->no_inv ?></td>
<td><?php echo $detil->kondisi ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default " data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
ajax_detail_barang function:
public function ajax_detail_barang($id)
{
$where = array
(
'id_barang' => $id,
'kondisi' => 'Ada'
);
$data['detail_barang'] = $this->modelku->get_by_id('detail_barang', $where)->result();
echo json_encode($data);
}
get_by_id function:
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
}
But when i click the button, the error appears "Kesalahan!" whats wrong my code?
The problem i see is in how u are using the returned data from ur model
public function get_by_id($table, $where)
{
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
return $query->row();
//at this point it already contains the data u need
}
but here u are using result();
$data['detail_barang'] = $this->modelku->get_by_id('detail_barang', $where)->result();
//i tried and u cant use result method if u already executed row method.
In short, remove result()
Hope my answer helps u.
I want to add confirm box by using JavaScript. So, here is the code that I have used. When I click on the Delete button, it shows me a Confirmation message and when I click Ok, it doesn't delete my row.
What is wrong with this? How can I fix this?
Here is the Index Page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Bootstrap core CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row"> <!-- Start Of The Row Class -->
<div class="col-md-8 col-sm-4 hero-feature"> <!-- Start Of The Col Class -->
<br><br>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include('ksdb.php');
// get results from database
$result = mysql_query("SELECT * FROM academic")
or die(mysql_error());
?>
<table class='table table-bordered'>
<tr class='danger'>
<th>ID</th>
<th>Name</th>
<th>Username</th>
</tr>
<?php
// display data in table
while($row = mysql_fetch_array( $result )) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><a href="AdminChangePw.php?id=<?php echo $row['id']; ?>" alt="edit" >Change</a></td>
<td><a href="AdminEdit.php?id=<?php echo $row['id']; ?>" alt="edit" >Edit</a></td>
<td><input type="button" onClick="deleteme(<?php echo $row['id']; ?>)" name="Delete" value="Delete"></td>
</tr>
<script language="javascript">
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id=' +id+'";
return true;
}
}
</script>
<?php
}
?>
</table>
</div> <!-- End Of The Col Class -->
</div> <!-- End Of The Row Class -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></script>
</body>
</html>
Change the id to 'delid'. You are calling the function as deleteme(delid).
So You Must use delid, instead of id.
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id="+delid; /*Change id to 'delid'*/
return true;
}
}
Use
window.location.href
Instead of window.location
There are a couple of problems with your function:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id='+id+'";// this should be delid, also bad quotes, also you want to set the href, not the location
return true;
}
}
Fixed:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id=" + delid;
return true;
}
}
I've a UI which adds data to the database via ajax. That data should reflect in my datatable without reloading the whole page or by just reloading the datatable. I've tried using t.api().ajax.reload() & t.ajax.reload() but it throws error in console like "Cannot read property 'reload' of undefined" or "t.api is not a function" i Don't know what am doing wrong here. Below are some reference
UI - Adding datas through add role btn which brings a pop up
Add Role Pop Up
HTML
<div id="roles" style="display: block" >
<ul class="tab-onebtn">
<li class="logouttab"> <a style="float: left;" id="myBtn"> Add Role </a> </li>
</ul>
<div class="table roles_table" >
<table class="example display" id="mytable" cellspacing="0" width="100%">
<thead>
<tr>
<th>Roles</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($resultRoles as $r) { ?>
<tr>
<td><?php echo $r->cptv_role; ?></td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<h1> Roles coming soon</h1>
</div>
<div id="myModal" class="modal" >
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<!-- <div class="modal-header">
<h2 style="text-align:center";>Add Role</h2>
</div>-->
<div class="modal-body">
<form action="" method="post" class="addRoleForm">
<?php if(!empty($this->session->flashdata('error')) ) { ?><div class='error' style="margin-top: -20px;"><h2><?php echo $this->session->flashdata('error'); ?> </h2></div><?php } ?>
<?php if(validation_errors() != false) { ?><div class='error'><?php echo validation_errors(); ?></div><?php } ?>
<div class="field-wrap">
<label>
Role <span class="req">*</span>
</label>
<input name="role" class="roleInput" type="text"required autocomplete="off"/>
</div>
<div id="result" class="msg" style="display:none;"></div>
<button class="button button-block submitbtn"/><span class="addRole" >Add Role </span> <span class="Added" style="display:none;"><b>Successfully Added </b></span></button>
</form>
</div>
<!-- <div class="modal-footer">
<h3>Modal Footer</h3>
</div>-->
</div>
</div>
Javascript
// Ajax post
$(document).ready(function() {
var t = $('#mytable').DataTable();
$(".addRoleForm").submit(function(){
event.preventDefault();
var str = $(this).serialize();
console.log();
jQuery.ajax({
type: "POST",
url: base_url+ "admin/roles/addRole",
dataType: 'json',
data: str,
success: function(result) {
if (result)
{
console.log(result);
// Show Entered Value
jQuery("div#result").show();
if(result.success){
// $('#mytable tbody').append('<tr><td>'+$('input[name="role"]').val().trim()+'</td><td></td></tr>');
// $('#mytable').DataTable();
t.api().ajax.reload();
jQuery("div.msg").html("<div class='success'><h2>"+result.success+"</div>");
setTimeout(function(){
span.click();
}, 2000);
}else{
jQuery("div.msg").html("<div class='error'><h2>"+result.error+"</h2></div>");
}
//var ref = $('#mytable').DataTable();
//setInterval( function () {
// ref.ajax.reload(); // user paging is not reset on reload
//}, 1000 );
setTimeout(function(){
jQuery("div#result").hide();
$(".roleInput").val('');
}, 2000);
}
}
});
});
});
Controller
public function addRole() {
if (empty($this->sessionData)){
// print_r($this->sessionData['id']); exit;
$this->index();
}
$post = $this->input->post();
$this->form_validation->set_rules('role', 'Role', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
$roleDet = $this->roles_model->checkCpRoles(array('cptv_role' => $post['role']));
if ($roleDet->num_rows()) {
$data['error'] = " Role already Exist.";
echo json_encode($data);
} else {
$result = $this->roles_model->addCpRoles(array('cptv_role' => $post['role']));
if ($result){
$data['success'] = " Successfully added the Role ";
echo json_encode($data);
} else {
$data['error'] = " Something went wrong ";
echo json_encode($data);
}
}
}
}
Can somebody help me please!?
Reload the datatable after ajax success like:
You're using old API: $().dataTable() (v1.9 and earlier) which is still available in DataTables v1.10. The old API returns jQuery object, so you should use .api() in order to use DataTable API methods:
oTable.api().ajax.reload();
// where oTable is the reference to datatable.
Since you have written some code in php I dont understand it much, But I can point the issue in your code. You are having a normal HTML table to which you apply the DataTable plugin.
Your code t.api().ajax.reload(); breaks because the DataTable is not fetching data via ajax, meaning your DataTable is not setup for a ajax based data, Its a normal HTML table.
What I suggest you is return the entire row that you need to append into the table (make sure all the columns are returned, right now you have only 2 columns in your table) in your ajax success method. Now all you have to do is add this new column into the dataTable and redraw the table.
Syntax to add a new row into the dataTable and redraw it is as below.
t.row.add(yourArrayGoesHere).draw( false );
So that means your response from the server must be a array. Example : ["Admin",""]
Test: Open your console window in the browser (press F12 to open)
and paste this code and hit enter. You must be able to see a new row with first cell having the value Admin.
t.row.add(["Admin",""]).draw( false );
Let me know if this helps.
This is the best example i have ever seen in which datatable is implemented with the Codeigniter framweork.
http://mbahcoding.com/tutorial/php/codeigniter/codeigniter-ajax-crud-using-bootstrap-modals-and-datatable.html