How to delete specific image from bootstrap modal using ajax? - php

I want to delete a specific image when user selected the red delete icon which is in the right side of each image .
screenshot-
ss after user click on deleted icon this shows up-
My php codes from where i took the img_id to delete and displaying all images-
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ON img_info.estate_infos_id = estate_infos.id where img_info.estate_infos_id = $mdoalid";
$stmt=$dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas=$stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($datas as $key => $data)
{ $pic = $data['image'];
$a=$data['img_id'];
?>
<img src="../<?php echo $pic ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delimg<?php echo $a; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i></a>
<?php echo $a?> // displays the id of each image displayed (wont display in production)
My modal code -
<!-- Modal -->
<div class="modal fade" id="delimg<?php echo $data['img_id']; ?>" tabindex="-1" aria-labelledby="delimglabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delimglabel">Delete Image</h5>
</div>
<div class="modal-body">
Are you sure you want to delete the image?
<?php echo $data['img_id'] ?>
</div>
<div class="modal-footer">
<button type="button" class="delbtn btn btn-sm btn-secondary text-white btn-danger">Delete</button>
//Here "delbtn" will trigger the ajax delete image from database
</div>
</div>
</div>
</div>
<?php } ?>
My ajax code which is i need to fix -
<script type="text/javascript">
$(document).ready(function() {
$(".delbtn").on("click", function(e) {
e.preventDefault();
alert("Working");
jQuery.ajax({
type: "POST",
url: "image-del.php",
data: < ? php echo $data['img_id'] ? > ,
success: function(response) {
alert('Image Deleted !');
},
error: function(response) {
alert('Image NOT Deleted !')
}
});
});
});
</script>
My mysql pdo code to delete image by id from database , this file name is "image-del.php"-
<?php
include_once 'connection.php';
if (isset($_POST['delbtn'])) {
$img_id = $_POST['img_id'];
$sql = "DELETE FROM img_info WHERE img_id=:img_id";
$stmt = $dbcon->prepare($sql);
$stmt->bindparam(':img_id', $img_id);
$stmt->execute();
?>
So, how can make the specific image get deleted by ajax properly?
-Thank you in advance

This is actually a two step process. Here's the idea:
First, as usual, render all the images along with their button to open the modal (the delete button to open the modal).
<?php foreach ($datas as $key => $data): ?>
<img src="../<?php echo $data['image'] ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delete-modal" data-imgid="<?php echo $data['img_id']; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i>
</a>
<?php endforeach; ?>
You do not need to serve the HTML modal inside the loop. You only need one modal. You don't need each modal for each image.
So just change it to this and put it in the bottom of the page:
<div class="modal fade" id="delete-modal" tabindex="-1" aria-labelledby="delimglabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delimglabel">Delete Image</h5>
</div>
<div class="modal-body">Are you sure you want to delete the image?</div>
<div class="modal-footer">
<button type="button" class="delbtn btn btn-sm btn-secondary text-white btn-danger" data-delete-imgid="">Delete</button>
</div>
</div>
</div>
</div>
After that, you need to trigger an event when the modal opens, get the image id and put it in the data attribute, so that it is used and can be accessed when you make the final request to delete it and send it to the server:
$('#delete-modal').on('show.bs.modal', function(e) { // when the delete modal opens
var imageId = $(e.relatedTarget).data('imgid'); // get the image id
$(e.currentTarget).find('.delbtn').attr('data-delete-imgid', imageId); // and put it in the delete button that calls the AJAX
});
Then like I said above the comments, don't echo the PHP image id in there. Use the ID that you applied in the button:
$(".delbtn").on("click", function(e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "image-del.php",
data: { delbtn: $(this).attr('data-delete-imgid') }
success: function(response) {
alert('Image Deleted !');
},
error: function(response) {
alert('Image NOT Deleted !')
}
});
});
This should serve as a general idea on how to pass the ID from the delete button to the modal, then finally to the server.

Related

how to add "loading" message into bootstrap modal until data fetch from database

I am using bootstrap modal to show to data which is fetched from the database. I have this code for load remote PHP data into bootstrap modal. it is work. but i need to add a loading message into the modal until data fetch from database. I have this code for load remote PHP data into bootstrap modal box
index.html
<script>
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_subjects.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
</script>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Subjects</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="fetched-data"> </div> <!--fetched dates here -->
</div>
<div class="modal-footer">
<button type="butZton" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
fetch_subjects.php
<?php
require 'db_connection.php';
if($_POST['rowid']) {
$id = $_POST['rowid'];
$sql = "SELECT * FROM subject where year=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class='list-group'>
<b>
<a href='notes?id=". $row['id'] ."' class='list-group-item list-group-item-action' target='_blank'>
" . $row["name"]. "
</a>
</b>
</div>
</button>";
}
}
else {
echo "no details.";
}
}
?>
I would do that this way:
$.ajax({
type : 'post',
url : 'fetch_subjects.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
},
beforeSend: function() {
$('#loader').show(); // Assuming that you have some loader defined
},
complete: function(){
$('#loader').hide(); //Hide this loader
},
});
<script>
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_subjects.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
beforeSend: function() {
$('.loader').show(); // Assuming that you have some loader defined
},
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
$('.loader').hide();
},
});
});
});
</script>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Subjects</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- loader -->
<div class="loader">
loading.............
</div>
<div class="fetched-data"> </div> <!--fetched dates here -->
</div>
<div class="modal-footer">
<button type="butZton" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

How to insert signature image into mysql database in php and retrieve the signature image

I am trying to insert the signature image data into the database and failed. I just found out how to pass the signature image into the folder in pc and i can see every image have different 'name.png' in the folder and i am thinking that the 'name.png' can be save in the database. I do not know how to make it successfully save into database.
This is my code of signature pad which i make it in a modal:
<div class="row mb-4">
<a href="#" class="btn btn-lg btn-success" data-toggle="modal" data-target="#basicModal">Client
Signature</a>
</div>
</div>
<div class="modal fade" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Client Signature</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="signArea" >
<h2 class="tag-ingo" style="font-size:30px;color:blue">Put signature below,</h2>
<div class="typed" ></div>
<p align="center">
<canvas class="sign-pad" id="sign-pad" width="300" height="100"></canvas></p>
</div>
</div>
<div class="modal-footer">
<button input="reset" class="btn btn-secondary" >Reset</button>
<button id="btnSaveSign" type="submit" name="submit" class="btn btn-primary">Submit</button>
This is the code that i save my signature image into a folder:
<script>
jQuery(document).ready(function() {
Main.init();
FormElements.init();
});
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true, drawBezierCurves:true, lineTop:90});
});
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
</script>
This is the save-sign.php code:
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = md5(date("dmYhisA"));
//Location to where you want to created sign image
$file_name = './doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
And this is the code where i retrieve the image in the folder:
<img src="<?php echo $image; ?>" class="sign-preview" />
The database name is 'appointment, and the image data should be in 'imagename'

Bootstrap modal window in Laravel app not showing

I'm writing a Laravel app and trying to implement a modal showing some details on an element. When I'm clicking on the link the backdrop is showing but not the modal window. In the network monitor of chrome it is showing the modal window in preview.
What's wrong?
Thank you in advance for your help!
Here is my code
index.blade.php
<td>
Details
</td>
modal.blade.php
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">#yield('title')</h5>
</div>
<div class="modal-body">
#yield('content')
</div>
<div class="modal-footer">
#yield('footer')
</div>
</div>
</div>
show.blade.php
#extends('layouts.modal')
#section('title')
Demo Modal
#endsection
#section('content')
<p>test</p>
#endsection
#section('footer')
<button type="button" data-dismiss="modal">Close</button>
#endsection
remote.js
$(document).on('ajax:success', function(e, xhr){
if(!$('#modal').length){
$('body').append($('<div class="modal" id="modal"></div>'))
}
$('#modal').html(xhr.responseText).modal('show');
});
ProjectController.php
public function show($id)
{
$project = Project::findOrFail($id);
return view('projects.show', compact('project'));
}
Hey never use HTML Element in making a clickable modals that has value on it.
I suggest you used add value on it , That can be "ID" then add modal attributes on it, Then boom everything is fine and working.
You need to specify the html id tag in your link.
I suggest you try this
<a data-toggle="modal" id="smallButton" data-target="#smallModal"
data-attr="{{ route('projects.show', $project->id) }}" title="show">
<i class="fas fa-eye text-success fa-lg"></i>
</a>
<!-- small modal -->
<div class="modal fade" id="smallModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="smallBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
<script>
// display a modal (small modal)
$(document).on('click', '#smallButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#smallModal').modal("show");
$('#smallBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
</script>
In your Remote.js file :
$(document).on('ajax:success', function(e, xhr){
if(!$('#modal').length){
$('body').append($('<div class="modal" id="modal"></div>'))
}
$('#modal').modal('show');
$('#modal').html(xhr.responseText);
});

Loading dynamic images on an bootstrap modal with ajax

I/m trying to load dynamic images on a bootstrap modal with ajax when a user clicks on different links on a page. Each link has an data-id that is used to show its relevant image in the modal body. It works fine for the first couple of links but starts to misbehave after 4-5 clicks. Later it starts showing previously loaded images when a link is clicked and the relevant image is shown after several seconds of the modal being triggered. Can anyone help me what I'm doing wrong with my code below:
My JS Code:
$(document).ready(function(){
$(document).on('click', '.viewPhoto', function(e){
e.preventDefault();
var pid = $(this).data('id'); // it will get id of clicked row
$("#photoContent").html("Please Wait...");
$.ajax({
url: "URL OF PAGE",
type: 'POST',
data: 'pid='+pid,
})
.done(function(data){
$('#photoContent').html(data); // load response
})
.fail(function(){
$('#photoContent ').html('Error');
});
});
});
And my modal HTML is:
<div id="viewPhotoModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×
</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body" id="photoContent"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And the HTML of Link is:
View Image
you should use cache: false in your ajax command.

Multiple deletion & edit of data in PHP

When I was trying to delete one data from the database but it would either delete the whole data in the database; it also the same problem for edit.
this code is for delete a user that will show a prompt when deleting a user:
<div id="delete_user<?php echo $id; ?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="alert alert-danger">Are you Sure yuo want to Delete this Data?</div>
</div>
<div class="modal-footer">
<a class="btn btn-danger" href="delete_user.php<?php echo '?id='.$id; ?>"><i class="icon-check"></i> Yes</a>
<button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-remove icon-large"></i> Close</button>
</div>
</div>
and this code here below is the actual delete from the database
<?php
include('dbcon.php');
$id=$_GET['id'];
mysql_query("delete from users where user_id='$id'") or die(mysql_error());
header('location:users.php');
?>
First check if value is set in $_GET['id'] then perform your action.
<?php
include('dbcon.php');
if(isset($_GET['id'])){
$id=mysql_real_escape_string($_GET['id']);
mysql_query("delete from users where user_id='$id'") or die(mysql_error());
}
header('location:users.php');
?>
your code seem to be okay, just check the debug the id value.
But still i strongly believe for such action don't pass id's in GET method. Use POST in ajax.
Below is the code with the ajax using POST method to pass the id to delete_user.php page
<div id="delete_user<?php echo $id; ?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="alert alert-danger">Are you Sure yuo want to Delete this Data?</div>
</div>
<div class="modal-footer">
<a class="btn btn-danger" onclick="deleteUser(<?php echo $id; ?>)" href="javascript:void(0)"> <i class="icon-check"></i> Yes</a>
<button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-remove icon-large"></i> Close</button>
</div>
</div>
Below the jquery ajax part
function deletUser(id) {
$.ajax({
url: 'delete_user.php',
method: 'POST',
data: {"id" : id},
success: function(data) {
// on success alter the div structure.....
}
});
}
below is code for your delete_user.php page
include('dbcon.php');
if(isset($_POST['id']) && $_POST['id'] != ''){
$id = (int)$_POST['id'];
mysql_query("delete from users where user_id=$id") or die(mysql_error());
}
header('location:users.php');

Categories