confirm delete swal not functioning - javascript

The swal stays that way infinetly
I am new to javascript. I am using swal to confirm delete of an order. the order is deleted correctly from the database and when I reload the page, I find the order deleted but the thing is that the page is not reloaded automatically.
echo ($paid == 0) ? "<td><p data-placement='top' data-toggle='tooltip' title='Delete'><a href='#' class='btn btn-danger btn-xs delete-confirm' id='" . $orderId . "'><span class='glyphicon glyphicon-trash'></span></p></td>" : "<td></td>";
<script type="text/javascript">
$('.delete-confirm').on('click', function() {
var orderId = $(this).attr('id');
console.log(orderId);
swal({
title: "Are you sure?",
text: "If you delete this post all associated comments also deleted permanently.",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes, delete it!",
}, function() {
setTimeout(function() {
$.post("delete.php", {
id: orderId
},
function(data, status) {
swal({
title: "Deleted!",
text: "Your post has been deleted.",
type: "success"
},
function() {
location.reload();
}
);
}
);
}, 50);
});
});
</script>
<script src="js/sweetalert.min.js"></script>
and the delete.php is here
<?php
session_start();
include('config.php');
if(!isset($_SESSION['username'])){
header("location: login.php");
}
$orderId = $_POST['id'];
$qry = "DELETE FROM orders WHERE order_id ='$orderId'";
$result=mysqli_query($connection,$qry);
?>
The order is deleted successfully from the database and the swal is not closed even if i wait infinite time and the page is not getting reloaded.
Please help me.

Which version of swal do you use?
Why are you using setTimeout, what are you waiting for?
I also use swal as deletion confirmation in the following way:
swal({
title: "Are you sure?",
text: "If you delete this post all associated comments also deleted permanently.",
type: 'warning',
showCancelButton: true,
showCloseButton: true,
reverseButtons: true,
focusCancel: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "cancel"
})
.then( function (willDelete) {
if (willDelete) {
$.post( "delete.php",
{ id: orderId },
function(data, status) {
swal({
title: "Deleted!",
text: "Your post has been deleted.",
type: "success"
};
}
)
} else {
toastr.info(Texxt('delet canceled), Texxt('Abbruch') + '.', {
closeButton: true,
progressBar: true,
});
}
}).catch(swal.noop);

Related

Show SweetAlert in delete function php

I'm trying to show the sweet alert in my DELETE FEATURE but sadly my code now is not working I already search for similar feature I see some but it not help me thought. Here is my code
<a id="<?php echo $id;?>" value="<?php echo $id;?>" name="delete" onclick="archiveFunction(this.id)">
<i class="glyphicon glyphicon-trash text-red"></i></a>
And this is my ajax request
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
$('#reloadpage').click(function() {
location.reload(true);
});
function archiveFunction(id) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Delete it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
// this is `post` request to the server
// so you can get the data from $_POST variables, says $_POST['delete'] $_POST['v_id']
$.ajax({
method: 'POST',
data: {'delete': true, 'id' : id },
url: 'user_del.php',
success: function(data) {
}
});
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
And this is my archive query . Don't bother about my query I set the status to 0 for me to archive one data and it will go to archive page. I just want to display the SWEET ALERT when I'm deleting the data or archiving it. Thanks in advance.
<?php session_start();
if(empty($_SESSION['id'])):
header('Location:../index');
endif;
include("../dist/includes/dbcon.php");
$id=$_REQUEST['id'];
$result=mysqli_query($con,"UPDATE accounts_at SET status = 0 WHERE id ='$id'")
or die(mysqli_error());
if ($result !== false) {
echo "<script type='text/javascript'>alert('Successfully deleted a account!');</script>";
echo "<script>document.location='index'</script>";
}
?>
Your UPDATED alert is in the wrong spot if you want it to run after the object is officially deleted on the server.
function(isConfirm){
if (isConfirm) {
// this is `post` request to the server
$.ajax({
method: 'POST',
data: {'delete': true, 'id' : id },
url: 'user_del.php',
success: function(data) {
//if you put it here it will run after the file is deleted
swal("Updated!", "Your imaginary file has been Deleted.", "success");
}
})
//if you put it here it will run before and even if your file is not deleted
// swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
Open up the develop console in your web browser. Does it give you any errors?
Do you get any alerts at all?
try this:
function archiveFunction(id) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function (isConfirm) {
if (!isConfirm) return;
$.ajax({
url: "delete.php",
type: "POST",
data: {
id: id
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}

How to Delete After Confirmation by Sweet-alert in Laravel...?

I have linked sweetalert plugin for my confirmation message. But it's not getting the confirmation command (onclick yes/confirm button).
This is my delete button:
<a id="demoSwal" href="{{ route('setting.website_type.destroy', ['id' => $websiteType->id]) }}" class="btn btn-light btn-sm btn-delete demoSwal" data-toggle="tooltip" data-placement="top" title="Delete This Type"><i class="far fa-trash-alt"></i></a>
This is My JS Code:
$(document).ready(function(){
$('.demoSwal').click(function(){
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your Data file has been deleted.", "success");
} else {
swal("Cancelled", "Your Data file is safe :)", "error");
}
});
});
});
This is my Controller Code:
public function destroy($id)
{
$delete_website_type = WebsiteType::find($id);
$delete_website_type->delete();
return redirect()->back();
}
Please Give me the solution...
you have to put .then()
let id = $("#your_id").val();
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}).then((isConfirm) => {
if(isConfirm) {
//you can just use fetchAPI
fetch(`route_to_your_destroy_method/${id}`)
.then(response => response.json()
.then(result => {
//your result
if (result == 'success') {
//alert success
}else {
//alert fail
}
}).catch(err => {console.log(err)});
}
});
and in your destroy method
$delete_website_type = WebsiteType::find($id)->delete();
if(delete_website_type) {
$message = 'success';
}else {
$message = 'fail';
}
return json_encode($message);
Give it a try
for delete button:---
<i class="far fa-trash-alt"></i>
in Jquery
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('/setting/website_type/destroy')}}",
data: {id:id},
success: function (data) {
//
}
});
});
});
and
public function destroy(Request $request)
{
$delete_website_type = WebsiteType::find($request->id)->delete();
return redirect()->route('website.index')
->with('success','Website deleted successfully');
}
i have updated my answer try this one.

after clicking a button of sweet alert call php file

I am trying to call a php file after clicking a button in the sweet alert. This function is the confirmation of Logging the account. Sample process is when you log out the active account, there will be a pop-up message that was the sweet alert, and if you click OK button, then it should have destroyed the session of the user. Can someone help me with this?
Here is my code:
<a href="javascript:swal({title:'Logout',
text:'Do you want to logout this Account?'
, icon:'warning',
buttons: true,
dangerMode: true}).then((willOUT) => {
if (willOUT) {
url: 'page_logout.php', {
icon: 'success',
});
}
});"
class="nav-item dropdown-item">
Log out
</a>
see the console
This would help you. It can take you to page_logout.php
And there is also some error in your swal code which you have written in
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<a href="#" id="a_id">Logout</p>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#a_id").click(function(){
swal({title:'Logout',
text:'Do you want to logout this Account?',
icon:'warning',
buttons: true,
dangerMode: true
})
.then((willOUT) => {
if (willOUT) {
window.location.href = 'page_logout.php', {
icon: 'success',
}
}
});
});
});
</script>
</body>
</html>
or if you want to show message in the same page in which there is logout button, then instead of url in your question do ajax request to page_logout.php. Hope it will help you.
try js:
<button type="button" onclick="logout('<?php echo $SESSION['user']['userId'] ?> ')" class="btn-danger">logout</button>
function logout(id) {
swal({
title: "Do you want to logout this Account?",
type: "error",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
userLogout(id);
}
});
}
function userLogout(id) {
$.post(base_url + "fileName/method_name", {id: id}, function (data) {
if (data === "1") {
}
else if (data === "0") {
swal("", "Error to logout user.", "warning");
} else {
swal("", data[0], "error");
}
});
}
You can use logout event with function
<script src="https://unpkg.com/sweetalert2#7.8.2/dist/sweetalert2.all.js"></script>
<a onClick="logout()">Logout</a>
<script>
function logout(){
swal({
title: 'Logout',
text: 'Do you want to logout this Account?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: 'No.'
}).then(() => {
if (result.value) {
// Call ajax page_logout.php File
} else {
// Close alert
}
});
}
OR
functio logout() {
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!'
}).then(function() {
swal(
'Deleted!',
'Your file has been deleted.',
'success'
)
})
}
</script>

Laravel 5.2 - Sweet Alert confirmation box

I have Categories listed in a view. A delete category button is also there in the view which does work and deletes the category when clicked.
What I want to do is before deleting a category, a sweet alert dialog to pop up and ask for confirmation. If confirmed, it should go to the defined route and delete the category.
The delete link is defined like this:
<a id="delete-btn" href="{{ route('admin.categories.destroy', $category->id) }}" class="btn btn-danger">Delete</a>
and the script is defined like this:
<script>
$(document).on('click', '#delete-btn', function(e) {
e.preventDefault();
var link = $(this);
swal({
title: "Confirm Delete",
text: "Are you sure to delete this category?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: true
},
function(isConfirm){
if(isConfirm){
window.location = link.attr('href');
}
else{
swal("cancelled","Category deletion Cancelled", "error");
}
});
});
</script>
However, when I click the delete button it deletes the category, but the sweet alert message doesn't show up.
The route is defined as following:
Route::get('/categories/destroy/{category}', [
'uses' => 'CategoriesController#destroy',
'as' => 'admin.categories.destroy',
]);
and the controller function is defined as:
public function destroy(Category $category)
{
$category->delete();
//this alert is working fine. however, the confirmation alert should appear
//before this one, which doesn't
Alert::success('Category deleted successfully', 'Success')->persistent("Close");
return redirect()->back();
}
Any help would be appreciated. Thanks.
Try this:
<script>
var deleter = {
linkSelector : "a#delete-btn",
init: function() {
$(this.linkSelector).on('click', {self:this}, this.handleClick);
},
handleClick: function(event) {
event.preventDefault();
var self = event.data.self;
var link = $(this);
swal({
title: "Confirm Delete",
text: "Are you sure to delete this category?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: true
},
function(isConfirm){
if(isConfirm){
window.location = link.attr('href');
}
else{
swal("cancelled", "Category deletion Cancelled", "error");
}
});
},
};
deleter.init();
</script>
EDIT: From your comment at #kalyan-singh-rathore's answer, I think you're not properly injecting the script in your blade template. If you're extending a base layout, make sure you've included the script or yielded it from a child layout.
Write anchor in below way.
Delete
Now in URL select change href to customParam.
function (isConfirm) {
if (isConfirm) {
window.location = link.attr('customParam');
} else {
swal("cancelled", "Category deletion Cancelled", "error");
}
}
Basically in your case both href and event lisner are on click.
Try this one it worked out for me :)
document.querySelector('#promote').addEventListener('submit', function (e) {
let form = this;
e.preventDefault(); // <--- prevent form from submitting
swal({
title: "Promote Students",
text: "Are you sure you want to proceed!",
type: "warning",
showCancelButton: true,
// confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false,
dangerMode: true,
}).then((willPromote) => {
e.preventDefault();
if (willPromote.value) {
form.submit(); // <--- submit form programmatically
} else {
swal("Cancelled", "No students have been promoted :)", "error");
e.preventDefault();
return false;
}
});
});

How To Use Sweet alert

This Is My HTML Code
I Have Two Input Button That I Want To Show Sweet Alert When a user Clicks on any Button
<tr class="examples odd" id="UserId_1" role="row">
<td class="sorting_1">1</td>
<td>admin</td><td>Mohammad</td>
<td>Farzin</td><td class="warning"><input type="button"
value="Delete" class="sweet-5" id="btn_Delete1"></td>
</tr>
<tr class="examples even" id="UserId_5" role="row">
<td class="sorting_1">2</td>
<td>11</td><td>11</td>
<td>11</td><td class="warning"><input type="button" value="Delete" class="sweet-5"
id="btn_Delete5"></td>
</tr>
Script
$(document).ready(function () {
document.querySelector('td.warning input').onclick = function () {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
};
});
Only The First Input Button Shows Sweet Alert, but
when I click the second button nothing happens
You were probably using SweetAlert version 2 and your code applies to version 1.
This should work:
swal({
title: 'Are you sure?',
text: 'Some text.',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: 'No.'
}).then(() => {
if (result.value) {
// handle Confirm button click
} else {
// result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
}
});
<script src="https://unpkg.com/sweetalert2#7.8.2/dist/sweetalert2.all.js"></script>
Source:
Migration from Swal1 to Swal2
Try this
$(document).ready(function () {
$('body').on('click', 'td.warning input', function () {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
});
Check Fiddle
http://jsfiddle.net/hoja/5a6x3m36/5/
If you want sweet alert on click of any button then change your code like below:
$(document).ready(function(){
$(document).on('click', 'button', function(){
Swal.fire({
type: 'success',
title: 'Your work has been done',
showConfirmButton: false,
timer: 1500
})
});
});
with sweet alert it is more easy for example i fave a link what i need is to call onclick function and make sure i included sweetalser.css and sweetalert.min.js i hope this will work for you
<a onclick="sweetAlert('Greetings', 'Hi', 'error');" class="" data-toggle="modal" href='#modale-id'><i class="fa fa-fw fa-plus"></i>Streams</a>
You are only selecting the first element that matches 'td.warning input' selector, that's why nothing happens to the second element.
Try querySelectorAll('td.warning input') method.
This returns an array and you can loop through the array to set Event Listeners.
window.onload=function()
{
swal({ title: "PopOutTitle", text: "Your FIRST Name:", type: "input", showCancelButton: true, OnConfirm:school();
animation: "slide-from-top", inputPlaceholder: name }, function(inputValue){ if (inputValue === false) return false;
if (inputValue === "") { swal.showInputError("You need to write something!"); return false }
document.getElementById("name").innerHTML=inputValue || "Unknown";
});
}
function school(){
swal({ title: "PopOutTitle", text: "Your last Name:", type: "input", showCancelButton: true,
animation: "slide-from-top", inputPlaceholder: name }, function(inputValue){ if (inputValue === false) return false;
if (inputValue === "") { swal.showInputError("You need to write something!"); return false }
document.getElementById("name").innerHTML=inputValue || "Unknown";
});**I want to show multiple swal popout so I want to call the school function when Ok Button is clicked. How can I do this?**
<script>
$(document).ready(function(){
$('.btn-danger').on("click", function(){
swal({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var id = $('.btn-danger').attr('data-id');
var cur_row = this;
$.ajax({
type: 'POST',
url: "{{url('/product_delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true)
{
swal("Done!", results.message, "success");
setTimeout(function(){
location.reload()
}, 2000);
}
else
{
swal("Error!", results.message, "error");
}
}
});
}
});
});
});
</script>
/* Add link in head section */
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.all.min.js"></script>
The Below examples are taken from https://sweetalert2.github.io/.
Get the latest version of sweetalter2 from here https://www.bootcdn.cn/limonte-sweetalert2/
Displaying validation error
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script src="https://cdn.bootcdn.net/ajax/libs/limonte-sweetalert2/11.7.0/sweetalert2.all.js"></script>
</head>
<body>
<script>
Swal.fire({
icon: 'error',
title: 'Validation Error!!!',
text: 'Passwords Did not Match!',
footer: 'Why do I have this issue?'
})
</script>
</body>
</html>
Display custom html
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script src="https://cdn.bootcdn.net/ajax/libs/limonte-sweetalert2/11.7.0/sweetalert2.all.js"></script>
</head>
<body>
<script>
Swal.fire({
title: '<strong>HTML <u>example</u></strong>',
icon: 'info',
html:
'You can use <b>bold text</b>, ' +
'links ' +
'and other HTML tags',
showCloseButton: true,
showCancelButton: true,
focusConfirm: false,
confirmButtonText:
'<i class="fa fa-thumbs-up"></i> Great!',
confirmButtonAriaLabel: 'Thumbs up, great!',
cancelButtonText:
'<i class="fa fa-thumbs-down"></i>',
cancelButtonAriaLabel: 'Thumbs down'
})
</script>
</body>
</html>

Categories