I'm using a PHP script to read data from a database and create an image gallery based on the results using Bootstrap Cards. Now I would like to have the possibility to delete data from the gallery. I finally found a way to do this -
PHP code:
[...]
echo "<div class='col-sm-4'>";
echo "<div class='card-deck'>";
echo "<div class='card' id='id_".$uploads[$i]['id']."'>";
echo "<img class='card-img-top' src='".$imagePath.$uploads[$i]['md5']."_tn.jpg' alt='Card image cap'>";
echo "<div class='card-img-overlay'><a class='close' href='#'>×</a></div>";
echo "<div class='card-body'>";
[...]
Javascript:
$(document).ready(function(){
$('.close').click(function(){
var target = $(this).parent().parent().attr('id');
$.ajax({url:'delete.php?id=' + target.replace('id_', '')});
location.reload();
});
});
This works perfectly fine, but I would like to include a Bootstrap Modal before actually deleting the picture from the gallery.
HTML modal code:
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete picture</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Do you really want to delete this picture?</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="deletePic" class="btn btn-danger">Delete Picture</button>
</div>
</div>
</div>
</div>
PHP code:
[...]
echo "<div class='col-sm-4'>";
echo "<div class='card-deck'>";
echo "<div class='card' id='id_".$uploads[$i]['id']."'>";
echo "<img class='card-img-top' src='".$imagePath.$uploads[$i]['md5']."_tn.jpg' alt='Card image cap'>";
echo "<div class='card-img-overlay'><a class='close' data-toggle='modal' data-target='#deleteModal' href='#'>×</a></div>";
echo "<div class='card-body'>";
[...]
Since the modal is now an additional step between the click on the X button and the actual delete my Javascript will not work anymore. Could someone please let me know how I can hand over the picture ID to the modal and in the next step delete the picture?
Thanks!
Simply you can do this:
$('a.close').click(function(){
var target = $(this).parent().parent().attr('id');
var pictureId = target.replace('id_', '');
$("#deletePic").data('picture-id', pictureId);
$("#deleteModal").modal("show");
});
Above code, we changed something. Firstly we removed ajax request. After that, we assigned picture id to delete button in the modal. After that, we opened the #deleteModal
Now, we know #deletePic has picture's ID number.
If we want to delete picture when clicked #deletePic button, we should use this:
$("#deletePic").on("click", function() {
var pictureId = $(this).data('picture-id');
$.ajax({url:'delete.php?id=' + pictureId});
});
And you shouldn't miss that, there are two .close class.
Firstly anchor has .close class that you want to use it. Also, bootstrap's modal contains .close class. So you should work ELEMENT.CLASSNAME if there are different elements has the same class.
I hope this will work for you.
Related
i have a php app with 3 table, each one have multiple row with button for each row to get a form for the affected data
the idea is to give a value for the modal to have as much column as in the affected table.
until now, i tried to have one form with button fo each table, with different value, and testing it in php to use the correct table for for the column as below in the code (it's a test webpage so there is just one button, i'm just trying to open a modal manually after testing a php value ) :
<body>
<form action="" method="post">
<button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-
target="#CreateInfra" name="der">
Launch demo modal
</button>
</form>
<script>
function modal(){
$("#myModal").modal('show');
}
</script>
<div class="bs-example">
<!-- Modal HTML -->
<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>This is a simple Bootstrap modal. Click the "Cancel button", "cross icon" or
"dark gray area" to close or hide the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data
dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
<?php
if (isset($_POST['der'])){
$value = 1;
var_dump($value);
}
else{
$value=2;
var_dump($value);
}
if ($value == 1){
echo "<script>modal()</script>";
}
?>
</body>
the thing is , when i hit the button, i see my page loading something for maybe 0.4 second but nothing happen.
is there any way to do this or i should use something else ?
You can do something like this as long as you want it to decide on the page load
<script>
function modal(val){
let options = [];
var myModal = new bootstrap.Modal(document.getElementById('exampleModal'))
if (val == 0){
myModal.show()
}
}
</script>
<?php $val = 0; ?>
<?php echo "<script>modal(".$val.")</script>" ?>
Other than that you would have to do it through a fetch request or AJAX because php and JS can't directly talk to each other
I have a list update part in my php where the ajax will update the list. The list is generated through sql queries and in a while loop. So it creates n number of list based on database values. Now I have a button on every list which will open up a modal box.
The update is done through set interval function below
var int = startinterval();
function startinterval() {
interval = setInterval(fetch_list, 1000);
return interval;
}
function fetch_list() {
var action = "fetch_data";
$.ajax({
url: "list.php",
method: "POST",
data: {
action: action
},
success: function(data) {
$('.list').html(data);
}
})
}
My Html where the data is updated to the list class
<div class="col-lg-12 list" style="overflow-y: auto;height: 400px;">
Now my problem is when i click the button on the list (as mention earlier) which should normally open up the modal box. Due to setInterval constantly updating the list every sec, the modal when open dissapears and goes hidden.
So what I'm trying is when I click the button to open the modal, it should stop the setinterval function. The setinterval should come back running once I click the cancel button inside the modal.
I tried many ways to clearinterval(), but no success. So expecting someone's help for me to get the wheels rolling.
Thanks in advance.
UPDATE:
my list would look like the below screenshot.
My list.php
if($_POST["action"] == "fetch_data")
{
echo fetch_list($connect);
}
function fetch_list($connect)
{
if(!$_SESSION['id']){
$output = '<ul class="list-unstyled"><h4>Please Select a Programme</h4></ul>';
return $output;
}else{
$query = "
SELECT * FROM list_programme
WHERE pid = '".$_SESSION['id']."'
ORDER BY pid ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
if($row["user"] == $_SESSION["uid"])
{
if($row["pstatus"] == '2')
{
$tickstatus = 'color:white';
$pcontrol = 'bg-success';
$pname = $row["pname"];
$border = 'border-color:#999;';
$pid = $row['pid'];
$notification = 'incomplete';
}
else
{
$pname = $row["pname"];
$pid = $row['pid'];
$notification = 'complete';
}
}
else
{
}
$output .= '
<div class="x_panel">
<button class="btn btn-round button-pcontrol '.$pcontrol.'" id="'.$pid.'" value="'.mb_strimwidth($pname, 0, 21, "...").'" data-notification="'.$notification.'" onClick="markcheck(this.id,this.value,this.dataset.notification)" style="'.$border.'"><i class="material-icons" title="Mark Completed" style="'.$tickstatus.'">check</i></button><span class="pname">'.$pname.'</span>
<span class="pcontrolbuttons">
<button class="btn btn-round button-pcontrol" id="programme" onClick="stopinterval()" data-id="'.$pid.'" data-toggle="modal" data-target="#programme'.$pid.'"><i class="material-icons" title="Assign users">person_add</i></button>
<button class="btn btn-round button-taskcontrol" data-id="'.$pid.'" data-value="'.mb_strimwidth($pname, 0, 21, "...").'" onClick="deleteprgm(this.dataset.id,this.dataset.value)"><i class="material-icons" title="Delete Task">delete</i></button>
</span>
</div>
<!--Modal -->
<div id="programme'.$id.'" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Add to this programme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Some Input elements, Drop downs, etc.,
</div>
<div class="submit-section">
<button type="button" class="btn btn-success submit-btn" id="addnusers"><i class="glyphicon glyphicon-plus"></i> Add Users</button>
<button type="button" class="btn btn-primary submit-btn" id="closeassignee" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /Modal -->';
}
$output .= '</ul>';
return $output;
}
}
So what I'm trying is when I click the button to open the modal, it
should stop the setinterval function.
You always should stops the functions execution, otherwise it will call the AJAX once per second and change the content of the modal.
document.getElementById('#button').addEventListener('click', function(event) {
event.preventDefault();
clearInterval(int);
// open modal
});
The setinterval should come back running once I click the cancel
button inside the modal.
document.getElementById('#cancel').addEventListener('click', function(event) {
event.preventDefault();
startinterval();
});
After searching for many resources, I had no luck to fix my issues with SetInterval.
So instead I modified my code to use setTimeout function. And the main drawback is this will not do live updates but once some button are clicked to modify the contents, the ajax success will call the setTimeout function and my list will be updated. So for time being the purpose is served.
Thanks for all the response.
Below is the single piece of code I Modified instead of a setInterval function
setTimeout(fetch_list, 1000);
The following function is able to open only one modal since it uses element ID.
How do I expand this function to open multiple modals?
HTML / PHP part of the code (Notice the that is supposed to open the model)
$getUsers = 'SELECT * FROM users';
$result = $pdo->prepare($getUsers);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($row['usergroup'] === "Admin") {
echo "<tr class='table-danger'>";
} else {
echo "<tr>";
}
echo "<td><center>" . $row['username'] . "</center></td>";
echo '<td><center>View</center></td>';
echo "</tr>";
}
Modal
<div class="modal fade" id="userInfoModal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Info</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="userModalBody" class="modal-body">
</div>
</div>
</div>
</div>
Javascript
$(document).ready(function() {
$('#openUserInfoModal').on('click',function(){
var dataURL = $(this).attr('data-href');
$('#userModalBody.modal-body').load(dataURL,function(){
$('#userInfoModal').modal({show:true});
});
});
});
Once again, the first row that is displayed, you can click the a href and it will open the modal and display the user info. After the first row, clicking the a href does nothing, and does not open the modal.
Also if you delete the first row / delete the user, and the second row now becomes the first one, you can click the a href and it'll display the users data.
I'm really not sure what is causing this issue, but thanks for any help.
The reason for this, is that you are duplicating the id of the a element. So, when you click on any of them, jQuery is actually using only the first one. So, you would need to change it, so as instead of using an id, you would use a class to open the modal.
PHP
$getUsers = 'SELECT * FROM users';
$result = $pdo->prepare($getUsers);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
if ($row['usergroup'] === "Admin") {
echo "<tr class='table-danger'>";
} else {
echo "<tr>";
}
echo "<td><center>" . $row['username'] . "</center></td>";
echo '<td><center>View</center></td>';
echo "</tr>";
}
jQuery
$(document).ready(function() {
$('.openUserInfoModal').on('click',function(){
var dataURL = $(this).attr('data-href');
$('#userModalBody.modal-body').load(dataURL,function(){
$('#userInfoModal').modal({show:true});
});
});
});
After a button is selected on a fresh page, all information are there, but whenever another is clicked, the first info is still there and wont change until the page is refreshed.
Help me pass this will ya?
button
<?php while($b = mysqli_fetch_assoc($equery)): ?>
<button type="button" onclick="modal(<?=$b['id'];?>)" class="w3-btn w3-border" style="width: 260px; display: inline-block; margin: 9px">
<img src="">
<h3><?php echo $b['product'];?></h3>
<h5>Descritopm</h5>
<h6></h6>
</button>
<?php endwhile;?>
js:
function modal(id){
var data = {"id" : id};
jQuery.ajax({
url : <?=BASEURL;?>+'includes/modal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#mod').modal('show');
},
error: function(){
alert("IDK")
}
});
}
modal:
<?php
require_once '../core/init.php';
$id = $_POST['id'];
$id =(int)$id;
$sql = "SELECT * FROM aisle WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
?>
<!-- Modal -->
<?php ob_start();?>
<div id="mod" class="modal fade" role="dialog" tabindex="-1">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title w3-center"><?=$product['product'];?></h3>
</div>
<div class="modal-body">
<p><?=$product['aisle'];?></p>
<p>$<?=$product['price'];?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo ob_get_clean();?>
The problem is here
jQuery('body').append(data);
This line will append more modal and many modals will appear on your page. You should follow this way. Create a div tag called contents_from_ajax inside body tag and then use this.
jQuery('#contents_from_ajax').html(data);
This code will remove all old modals and create a new one instead of append, and then it will work fine.
Hope this help
I want to create modal button for delete a user gets from a foreach in the html body.
The modal opens an iframe with a form. The iframe url seems like
<iframe src=<?php echo base_url('index/page/');?> witdth....
I want to pass to the iframe src the php variable contains an userid, for example:
<iframe src=<?php echo base_url('/index/page/'+username);?> witdth....
First code works fine and it shows the view but no variable passed with the second code.
I use a javascript for open the modal and get the ID variable.
The link:
<a data-toggle="modal" data-target="#myModal" data-detail-id=<?php echo $users->username; ?>>
And the js:
<script>
$(".myModal").on("click", function(e) {
var username;
e.preventDefault();
username = $(this).data("detail-id");
});
</script>
How to get the detailId to the iframe src to pass the variable to the index/page?
Thanks a lot.
EDIT---
I will post full code, the ovjective is to pass a PHP variable got in a foreach to a modal windows in that calls a iframce to other view to use the variable:
<a data-toggle="modal" data-target="#myModal" data-detail-id=<?php echo $users->username; ?>></a>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<script>
$(".myModal").on("click", function(e) {
var username;
e.preventDefault();
username= $(this).data("detail-id");
});
</script>
<center><iframe src=<?php echo base_url('/index/page/'+username);?> width="500" height="380" frameborder="0" allowtransparency="true"></iframe></center>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Thanks!!
You are mixing JS and PHP together:
<iframe src=<?php echo base_url('/index/page/'+username);?> width.... ( note the + )
<iframe src=<?php echo base_url('/index/page/'.$username);?> width.... ( append with . operator )
In PHP, you append with . operator
Also if you are looking for easy solution to delete smoething (ex. user) you can use something like this in your view:
<script>
function doconfirm()
{
job=confirm("Are you sure, to delete?");
if(job!=true)
{
return false;
}
}
</script>
<?php foreach ($users as $user_detail): ?>
Delete user<br>
<?php endforeach ?>
and from your user model try somethig like:
public function delete($user_id)
{
$query = $this->db->where('user_id', $user_id);
return $query = $this->db->delete('users');
}
Hope this helps.