Hello guys I'm trying to delete a record/row from my table using a modal delete confirmation. This is what I've tried so far:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
</script>
<table class="table table-bordered">
<?php
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
<tr>
<td><a href="project-detail.php?code=<?php echo $project; ?>">
<?php echo $project; ?></a></td>
<td><?php echo $desc; ?></td>
<td><a href="update-project.php?code=<?php echo $project; ?>" title="Update record">
<i class="icon-edit icon-white">
</i>
</a></td>
<td><a href="#<?php echo $project; ?>"
id="<?php echo $project; ?>"
data-id="<?php echo $project; ?>"
class="btn-show-modal" data-toggle="modal" title="Delete record">
<i class="icon-trash icon-white"></i></a></td>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
</div>
</div>
</tr>
<?php
}
?>
</table>
But the problem is, when I am about to delete the last row the one that gets deleted is the first row. Why is it like that? Any ideas? Help is much appreciated. Thanks.
The problem lies in the modal generation and passing the $project value.
You are using a loop as
for($i=0; $row2 = $stmt2->fetch(); $i++){
$project = $row2['project_code'];
$desc = $row2['description'];
?>
And inside the above loop you are generating the modals so basically you will have many modals which are equal to the num of rows in the query.
Now all of them are having the same "id" i.e. "dialog-example" and once you click on the delete it pop ups the first modal from the DOM and is deleting wrong data.
Solution
For each modal you give the id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the blow code
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
});
Get the id of the element using attr("id") and append this at the end of
"dialog-example_"+{id you received}
The same thing you need to do for the hide modal as well.
UPDATE ON HOW TO DO IT
Give the modal div id as
<div class="modal hide fade" id="dialog-example_<?php echo $project; ?>">
Then in the click function to as
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
Change
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="btn-delete">Yes<a>
to
<a href="delete-project.php?code=<?php echo $project; ?>"
class="btn btn-danger" id="<?php echo $project ;?>">Yes<a>
AND finally
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
to
$(".btn btn-danger").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('hide');
});
because you generate modal for every row this is wrong !
and show modal(first modal show) this is wrong!(this delete first row)
create one modal and set parameter with jquery e.g
$(".btn-show-modal").click(function(e){
e.preventDefault();
$("#dialog-example").modal('show');
$("#dialog-example #btn-delete").attr('href','delete-project.php?code='+$(this).attr('data-id'));
});
good luck
On topic
Problem is you have multiple modals. But select it on 1 id. So jQuery will select the first value.
A solution would be to put the delete url in an hidden input field. Then when the user clicks the open delete modal you select the url and put it in the a tag.
Example time
JavaScript Part
$(function(){
$(".btn-show-modal").click(function(e){
// put the right url in the delete
$("#dialog-example .delete-url").attr('href', $(this).attr('data-delete-url');
$("#dialog-example").modal('show');
return e.preventDefault();
});
$("#btn-delete").click(function(e) {
$("#dialog-example").modal('hide');
});
});
PHP part
I assume $stmt is prepared etc
<ul>
<? foreach($stmt->fetchAll() as $record) : ?>
<li>
delete
</li>
<? endforeach; ?>
</ul>
<div class="modal hide fade" id="dialog-example">
<div class="modal-header">
<h5>Confirm Delete</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn btn-info">No<a>
<a class="delete-url btn btn-danger">Yes<a>
</div>
</div>
Code explaind
It is not handy to put an bootstrap modal in an foreach/for/while unless you change the id. But then again lot of duplicate code.
What the code does it changes the delete-url on the fly depending on which a the user clicked
Off topic
I highly recommend using the foreach for your iteration of the data records instead of a for loop.
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
for($i=0; $row2 = $stmt2->fetch(); $i++){ /** code **/}
would be
$stmt2 = $conn->prepare( "SELECT project_code, description
FROM tblprojects" );
$stmt2->execute();
foreach($stmt2->fetchAll() as $record){}
Because when you open the modal, it open the first #dialog-example div.
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
$(this).parent().find("#dialog-example").modal('show');
});
Related
I have a modal in bootstrap 5 that i'm trying to populate with custom data from a mysql database depending on the option i'm selecting.
So I have a table that is populated with some data using PHP and MYSQL. The last column of the table is a button called "Actions" and I want to have a modal opened when I press this button that is filled with the information from the row where I pressed the button (every row contains this button as the last column).
As you can see in the below code, I have the exact same code as I found out in the sollution in this question: Pass PHP variable to bootstrap modal
Here is my code:
In the main index file:
...
...
<tbody>
<?php $categories = Category::find_all();
foreach ($categories as $category) { ?>
<tr>
<th scope="row"><?php echo $category->id; ?></th>
<td><?php echo $category->cat_name; ?></td>
<td><?php echo $category->cat_creation_date; ?></td>
<td><?php echo $category->cat_created_by; ?></td>
<td><a type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#bsMyModal" data-id="<?php echo $category->id; ?>">Actions</a></td>
</tr>
<?php } ?>
</tbody>
...
...
Modal code (in the same file as the above table):
<div class="modal fade" id="bsMyModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Data</h4>
</div>
<div class="modal-body">
<div class="fetched-data"></div> //Here Will show the Data
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS code (just below the end of body in the same file)
</body>
<script>
$(document).ready(function(){
$('#bsMyModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_record.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Also the fetch_record.php file which is a basic file just to have this working:
<?php
require_once "backend/init.php";
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
echo $id;
}
?>
Now the problem.. nothing happens
The modal openes when I press the Actions button, but I don't get any information (in this specific case I should be getting the category id printed out before the "//Here Will show the Data" text in the modal code.
I looked at the console and I've seen this message:
ajax:681 Uncaught ReferenceError: $ is not defined
at ajax:681:1
(anonymous) # ajax:681
If i click the link at # ajax:681, it points me to this:
enter image description here
What am I doing wrong?...
Thank you!
Stupid mistake...
I tought about searching for the console error and come upon this:
Uncaught ReferenceError: $ is not defined?
And yes.. I was using the script before referencing the jQuery.. I moved it after the jQuery include and now it works.
Dumb
Im new here and I have some difficulties to make my code to work. Hope u guys can help me. Im displaying records form MySQL in a modal box in a table format. Each row has its own add (+) button generated via php loop which displays records that should be leter on, added to a different table using jquery on click event and AJAX. Each td row is provided with an input field with class name "idKont", but only the first one will be added after I click on the + / add button.
$('#add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); // ID of the customer that will be passed
var idKont = $('.idKont').val(); // ID of the contact person
$.ajax ({
url: "folder/insert_data.php",
method:"POST",
data:
{
id: ptId,
idKont: idKont
},
dataType:'text',
success: function(result) {
//$('#myModal').modal('hide');
$('#alert_modal').append( '<div class="alert alert-success">Success</div>' ).fadeIn(1000).fadeOut(4000);
}
})
})
and this is the HTML Code with PHP:
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:10px 50px;">
<p><span class="glyphicon glyphicon-lock"></span> Choose Contact Person</p>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" style="padding: 40px 50px;">
<form role="form" method="post">
<div id="alert_modal"></div>
<table class="table table-responsive">
<thead class="thead-light">
<tr>
<th>ID</th>
<th>Vorname</th>
<th>Name</th>
<th>Tel</th>
<th>Mobil</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $connser->prepare("SELECT ID, Vorname, Name, Tel, Mobil FROM Contactperson ORDER BY ID DESC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$kontID = $row['ID'];
?>
<tr>
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['Vorname']; ?></td>
<td><?php echo $row['Name']; ?></td>
<td><?php echo $row['Tel']; ?></td>
<td><?php echo $row['Mobil']; ?></td>
<td><input class="idKont" value="<?php echo $kontID; ?>" type="hidden" /></td>
<td><button type="submit" class="btn btn-success add_kontpers">+</button></td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error";
//echo "Error: " . $e->getMessage();
exit;
}
?>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
The modal box stays open and it shoud be, but if I click the first element on the top, then only this one will be added. I would like to have the oportunity to click for example one position on the list to add it to the table, the the second one, and so on, but if I click other butten then the first one then the modalbox will be closed and the website reloads. Any help or pinting in the right direction will be highly appreciated.
Two things, first you can't reuse the same ID and by having add_kontpers in a loop, you will reusing that.
So first, change that to a class and idAj doesn't exist in the provided code.
<button type="submit" class="btn btn-success add_kontpers">
Then make this change in your jQUERY
$('.add_kontpers').on("click", function(e) {
e.preventDefault();
var ptId = $('#idAj').text(); ?????????????????????
var idKont = $(this).parents("tr").find('.idKont').val(); // ID of the contact person
Javascript
$(document)
.on('click', 'button#add_kontpers', function(a){
a.preventDefault();
var button = $(this);
var row = button.closest('tr');
var id = row.find('input').val();
$.post("folder/insert_data.php", {id : id, idKont : id})
.done(function(response){
//Your response
})
})
I am displaying tickets and used while loop to display each on a table. Edit button is working fine for each loop however for the delete button I can't seem to pass the value of the ticket that I specifically want to delete. Function goes like this once the delete button is clicked it will go to a modal for confirmation of deletion but it always deletes the 1st row. I need to get the specific value of the ticket to pass to deleteconfirm.php Below is the code that I have used.
$stats = $_REQUEST['stats'];
$query20 ="SELECT * FROM user WHERE status='$stats' ORDER BY date_received
DESC";
$result2 = mysqli_query($datalog,$query20);
while( $row = mysqli_fetch_assoc( $result2 ) ){
if($row['task5']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'].'/'.$row['task3'].'/'.$row['task4'].'/'.$row['task5'];
}
elseif($row['task4']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'].'/'.$row['task3'].'/'.$row['task4'];
}
elseif($row['task3']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'].'/'.$row['task3'];
}
elseif($row['task2']!=''){
$tasks = $row['task'].'/'.$row['task1'].'/'.$row['task2'];
}
elseif($row['task1']!=''){
$tasks = $row['task'].'/'.$row['task1'];
}
elseif($row['task']!=''){
$tasks = $row['task'];
}
echo
"<tr>
<td>{$row['ticket']}</td>
<td>{$row['date_received']}</td>
<td>{$row['subject']}</td>
<td>{$row['property']}</td>
<td>$tasks</td>
<td>{$row['territory']}</td>
<td>{$row['loadername']}</td>
<td>{$row['seniorname']}</td>
<td>{$row['qaname']}</td>
<td><a href=editticket.php?supe=".$row['ticket']." target='_top'>
<span class='glyphicon glyphicon-edit'></span></a>
<button class='open-homeEvents' id='btnPopModal' href='#' data-
toggle='modal' data-target='#confirmdelete' data-
id=".$row['ticket']." > <span class='glyphicon glyphicon-trash'
style='color:red'></span></button>";
echo"
<div class='modal fade' id='confirmdelete' role='dialog'>
<form method='POST' action='deleteconfirm.php' id='delcon' >
<div class='form-group'>
<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'>Confirm Delete</h4>
</div>
<div class='modal-body'>
<p>Are you sure you want to Delete Ticket <b> <input
type='hidden' name='eventId' id='eventId'/>
<span id='idHolder' name='idHolder'></span>
</b>?</p>
<p>If Yes please confirm indicating reason below:</p>
<p><textarea id='res' name='res' required></textarea></p>
<input hidden id='delc' name='delc' value=".$row['ticket']."
/>
</div>
<div class='modal-footer'>
<button class='btn btn-default' href='#' type='submit'
target='_parent'>Yes</button>
<button type='button' class='btn btn-default' data-
dismiss='modal'>No</button>
</div>
</div>
</div>
</div>
</div>
</form>
</td>
</tr>\n";} ?>
Below is the code for deleteconfirm.php
<?php
session_start();
require_once('datalog.php');
$delc=$_POST['delc'];
$tak= $_POST['tak'];
$res=$_POST['res'];
if(isset($_REQUEST['delc'])&&$_REQUEST['delc']!=''
&&isset($_SESSION['SESS_USER_NAME'])){
$tickets=$delc;
$delid=$_SESSION['SESS_USER_NAME'];
$query22="SELECT * from memberinfo WHERE username='$delid'";
$result22=mysqli_query($datalog,$query22);
while( $row1 = mysqli_fetch_assoc( $result22 ) ){
$delby=$row1['full_name'];
}
$query23="SELECT * from user WHERE ticket='$delc'";
$result23=mysqli_query($datalog,$query23);
while( $row = mysqli_fetch_assoc( $result23 ) ){
$subject= $row['subject'];
$property= $row['property'];
$country= $row['country'];
$city= $row['city'];
$validity= $row['validity'];
$remarks= $row['remarks'];
$priority= $row['tagging'];
$territory= $row['territory'];
$status= $row['status'];
$date_received= $row['date_received'];
$loader= $row['loadername'];
$senior= $row['seniorname'];
$qa= $row['qaname'];
}
$query1="INSERT INTO deletehistory (iddeleted_by,deleted_by,deletereason,subject,property,task,country,city,validity,remarks,ticket,priority,status,date_received,loader,qa,senior,territory) values ('".$delid."','".$delby."','".$res."','".$subject."','".$property."','".$tak."','".$country."','".$city."','".$validity."','".$remarks."','".$delc."','".$priority."','".$status."','".$date_received."','".$loader."','".$qa."','".$senior."','".$territory."')";
$result1=mysqli_query($datalog,$query1);
}
$query4="DELETE FROM user WHERE ticket='$delc' ";
$result4=mysqli_query($datalog,$query4);
header("location: delete.php");
?>
Hope someone can enlighten me on this one, Thanks in advance!
You can use data-whatever in the button tag of delete e.g here
<button class='open-homeEvents' id='btnPopModal' href='#' data-
toggle='modal' data-target='#confirmdelete' data-
whatever="$row['ticket']" >
And use a jquery js to get the data in the modal
<script type="text/javascript">
$('#confirmdelete').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('#eventId').val(recipient);
})
</script>
i want to get images that i fetched from database in my page and show them again in div with id test by ajax i want to show fetched datas again in div with test id when i click on button with addCart class . i think i haveto get value of button that i set it to ids of products in my datbase . and my problem is how can i get id s in ajax code?
$(document).ready(function(){
$(".addCart").click(function(){
$.post(".addCart.val()",function(data){
$("#test").html(data).show();
});
});
});
<div id="test" style="background-color: grey"></div>
<?php while ($row = mysqli_fetch_array($products)):?>
<div class="span3">
<div class="product">
<div class="product-img">
<div class="picture">
<img src="images/<?php echo $row['image'] ?>" alt="" width="540" height="374" />
<div class="img-overlay">
توضیحات بیشتر
<button value="<?php echo $row['id']?>" class="btn buy btn-danger addCart">اضافه به سبد خرید</button>
</div>
</div>
</div>
<div class="main-titles no-margin">
<h4 class="title"><?php echo $row['price'] ?></h4>
<!--<h5 class="no-margin">محصول ویژه 434</h5>-->
</div>
<p class="desc"><?php echo $row['name']?></p>
<p class="center-align stars">
<span class="icon-star stars-clr"></span>
<span class="icon-star stars-clr"></span>
<span class="icon-star"></span>
<span class="icon-star"></span>
<span class="icon-star"></span>
</p>
</div>
</div> <!-- /product -->
<?php endwhile;?>
$(".addCart").click(function(event){
var id = event.target.val();
});
This will get an value of your button element. But is this id is a valid url to make a ajax call? I dont think so. Please checkout Jquery Docs before returning to work on this part of functionality
in your code you are not passing correct value to php file
please do correction in your code
$(document).ready(function(){
$(".addCart").click(function(){
var jq = $(this);
var cart_id = jq.val(); /* get cart value */
$.post("ajax.php",{cart_id:cart_id},function(data){
$("#test").html(data).show();
});
});
});
and fetch cart_id in php ajax.php file like this
<?php
if(isset($_POST['cart_id'])){
/* put your code here */
}
?>
I have a following data where I am showing data from database. When i click Comment a dialog appear, there i need to show data in modal from db. but for getting data from db i need msg_id in modal form.
<?php
$msg_id = $data['message_id'];
?>
<a data-toggle="modal" href="msg_id=<?php echo $msg_id; ?>#example" class="link_comment">Comment</a>
So here I want to pass msg_id to jquery modal form, where i can get data from db on the base of msg_id for that specific message and show it in modal box.
<div id="example" class="modal" style="display: none; ">
Your Message id : <?php echo $msg_id; ?>
</div>
So how can I pass $msg_id into jquery modal form.
php
<?php
$msg_id = 123; // testing mode
?>
html
<a data-toggle="modal" href="msg_id=<?php echo $msg_id; ?>#example" class="link_comment">Comment</a>
<div id="example" class="modal" style="display: none; ">
Your Message id : <span class="msg_id">?</span>
</div>
<script type="text/javascript">
$('a.link_comment').click(function(event) {
event.preventDefault();
var a = $(this);
var msg_id = 'fetched id'; // parse msg_id from a.attr('href')
$('div.' + a.attr('data-toggle')).show().find('span.msg_id').text( msg_id );
});
</script>