In my laravel project I am using sweet alert works fine but it is deleting my first-row record only I don't know what the problem is
this is my form
<td>
<form id="myform" class="delete-photo" method="POST" action="{{route('testimony.destroy', $testimony->id)}}">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
<div class="form-group">
<button type="submit" data-photo-id="{{$testimony->id}}"
class="submitdel btn btn-danger"
>Delete</button>
</div>
</form>
and this is my script
$('.delete-photo').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("action");
warnBeforeRedirect(linkURL);
});
function warnBeforeRedirect(linkURL) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#5c5856",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
document.getElementById("myform").submit();
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
}
);
}
This is because your form passing a same id each time. if you are looping in your record then the form must be loop thought. But this is not good practice. i would suggest you to use
<button type="submit" data-photo-id="{{$testimony->id}}" class="submitdel btn btn-danger">Delete</button>
in loop then the $testimony->id would be different with it's own id that is coming from database. Then get it's data-photo-id with Javascript on click event handler then pass this id to your controller and post the url.
okay suppor you are getting dynamic data from database and displaying it like
<table>
<tr>
<td>name</td>
<td>email</td>
<td><button type="submit" data-photo-id="1" class="submitdel btn btn-danger">Delete</button></td>
</tr>
<tr>
<td>name</td>
<td>email</td>
<td><button type="submit" data-photo-id="2" class="submitdel btn btn-danger">Delete</button></td>
</tr>
<tr>
<td>name</td>
<td>email</td>
<td><button type="submit" data-photo-id="3" class="submitdel btn btn-danger">Delete</button></td>
</tr>
</table>
then get the data-photo-id (replace this with your dynamic id) by using this way
<script>
$(function(){
$('.submitdel').on('click',function(){
// store current button into variable
var id = $(this).data('photo-id');
warnBeforeRedirect(id);
})
})
function warnBeforeRedirect(id) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#5c5856",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
window.location = 'http://yoursite.com/controllername/'+id
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
}
);
}
</script>
and replace window.location with the url you are want to use. Hope you get it now.
Related
public function destroy(Company $company)
{
Alert::question('Delete Record?', 'Cannot Undo! Are You Sure?');
if (session('status')) {
$company->delete();
}
return back()->with('status', 'Company Deleted!');
}
At the moment the record deletes with or without the Sweet Alert confirmation. I want the record deleted only after the Sweet Alert confirmation is clicked.
Just change button type from submit to button and trigger vai javascript function
<form action="{{ route('orders.destroy', $row->id) }}" method="post" class="d-inline">#csrf#method('DELETE')<button type="button" class="btn btn-sm btn-danger confirm-delete"><i class="fas fa-times"></i></button></form>
$(document).on('click', 'button.confirm-delete', function () {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
$(this).parent('form').trigger('submit')
} else if (result.isDenied) {
Swal.fire('Changes are not saved', '', 'info')
}
});
});
I was searching for an answer like you, and I came up with something works perfectly!
If the user is trying to delete something, it will show him warning alert to confirm the delete.. once he clicks on yes it will delete it and show another alert with success of deletion.
Here is how you can do it:
after installing RealRashid/Sweet-Alert and publish it you need to do this:
In your view:
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
//Sweet alert stylesheet
<link rel="stylesheet" href="sweetalert2.min.css">
</head>
<body>
//refer to rashid's docs
#include('sweetalert::alert')
//The delete button
<a class="btn btn-primary mb-1" href="{{ Route('movies.edit', $movie) }}">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ Route('movies.destroy', $movie) }}" method="post" class="ms-2 mb-1">
#csrf
#method('DELETE')
//The 'confirm' class is important to use in the JavaScript code
<button class="btn btn-danger confirm" type="submit">
<i class="bi bi-trash"></i>
</button>
</form>
//Add Sweetalert script lib
<script src="sweetalert2.all.min.js"></script>
<script>
//the confirm class that is being used in the delete button
$('.confirm').click(function(event) {
//This will choose the closest form to the button
var form = $(this).closest("form");
//don't let the form submit yet
event.preventDefault();
//configure sweetalert alert as you wish
Swal.fire({
title: 'هل أنت متأكد؟',
text: "لا يمكنك التراجع عن حذف الفلم",
cancelButtonText: "إلغاء",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'حذف'
}).then((result) => {
//in case of deletion confirm then make the form submit
if (result.isConfirmed) {
form.submit();
}
})
});
</script>
</body>
</html>
after doing the above code in your view, head to your controller and do this:
//Add use statement for rashid's alert
use RealRashid\SweetAlert\Facades\Alert;
//in your destroy function you can do this
public function destroy(Movie $movie)
{
$movie->genres()->detach();
$movie->delete();
return redirect()->route('movies.index')->with('success', 'تم حذف الفلم بنجاح!');
}
//with success will trigger rashid's alert to pop up and you customize the message in 'with' statement!
That's it! you don't need to do anything else or add Alert::success in the controller.. withSuccess works just fine.
i am using sweet alert method framework to show the alert when deleting but when i do this at destroy method return Request() or return $request it returns blank page with no requests or results i don't know why please help
here is my code
my route
Route::resource('brands',App\Http\Controllers\backend\brandController::class);
my table to view brands
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>brand name en</th>
<th>brand name ar</th>
<th>image</th>
<th>action</th>
</tr>
</thead>
<tbody>
#foreach ($brands as $brand)
<tr>
<td>{{$brand->brand_name_ar}}</td>
<td>{{$brand->brand_name_en}}</td>
<td>{{$brand->image}}</td>
<td>edit
<a href="{{route('brands.destroy',$brand->id)}}" id="delete"
class="btn btn-danger">delete</a>
</td>
</tr>
#endforeach
</tbody>
</table>
my sweet alert javascript code
<script>
$(document).ready(function(){
$(function (){
$(document).on('click','#delete',function(e){
e.preventDefault();
var link = $(this).attr('href');
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = link
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
});
});
});
});
</script>
my destroy method
public function destroy($id,Request $request)
{
return Request();
$brand = Brand::find($id);
}
How to use sweetalert confirm deleting in my project
i am using asp.net MVC core 5.0
I'm trying to make delete confirmation for category. When user click this button in Index.cshtml it will show delete confirmation for delete data or not, but delete confirmation just appear for while after that data deleted without the confirmation.
Index.cshtml side =
<tr>
<th>ID</th>
<th>Kategori</th>
<th>Sil</th>
<th>Düzenle</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.CategoryName</td>
<td>
<a asp-action="Delete" asp-controller="Category" asp-route-id="#item.Id" class="btn btn-danger" id="delete">Sil</a>
</td>
<td><a asp-action="Edit" asp-controller="Category" asp-route-id="#item.Id" class="btn btn-primary">Güncelle</a></td>
</tr>
}
Controller side =
public IActionResult Delete(int id)
{
var category = _unitOfWork.categoryRepo.Get(x => x.Id == id);
_unitOfWork.categoryRepo.Delete(category);
_unitOfWork.Save();
return RedirectToAction("Index");
}
js side =
<script src="/adminlte/vendor/jquery/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
sweetalert =
<script>
function confirm() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("deleted!", {
icon: "success",
});
} else {
swal("category is safe!");
}
});
return false;
}
Merhaba/Hi İbrahim,
Change your code like below;
<td><div><form asp-action="Delete" method="post" asp-controller="Category" asp-route-id="#item.Id"><button type="button" class="btn btn-danger" onclick="return functionConfirm(this)">Delete</button></form>
</div>
</td>
and
#section Scripts{
<script>
function functionConfirm(event) {
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: 'btn btn-success',
cancelButton: 'btn btn-danger'
},
buttonsStyling: false
})
swalWithBootstrapButtons.fire({
title: 'Emin misiniz?',
text: "Bu işlem geri alınamaz!",
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Evet, sil!',
cancelButtonText: 'Hayır, iptal',
reverseButtons: true,
timer: 3000
}).then((result) => {
if (result.isConfirmed) {
$("form").submit();
swalWithBootstrapButtons.fire({
title: 'Silindi!',
text :'Kategori silindi.',
icon: 'success',
timer:'2000'
}
)
} else if (
/* Read more about handling dismissals below */
result.dismiss === Swal.DismissReason.cancel
) {
swalWithBootstrapButtons.fire(
'İptal edildi',
'',
'error'
)
}
})
}
</script>
}
Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');
I want to perform the delete operation with sweetalert2. But after clicking the confirm button nothing is happening. Form is not submitted. What's the error i'm getting?
function deleteTag(id) {
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
reverseButtons: true
}).then((result) => {
if (result.value) {
event.preventDefault();
document.getElementById('delete-form-' + id).submit();
} else if (
// Read more about handling dismissals
result.dismiss === swal.DismissReason.cancel
) {
swal(
'Cancelled',
'Your data is safe :)',
'error'
)
}
})
}
<button class="btn btn-simple btn-danger btn-fab btn-icon" type="button" onclick="deleteTag({{ $tag->id }})"><i class="material-icons">delete</i>
</button>
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf #method('DELETE')
</form>
I got this console error after selecting confirm delete button.
enter image description here