Sweet Alert Delete Confirmation with a href - javascript

Im using PHP, and Sweet alert for a delete confirmation. Problem is that it is deleting before showing the sweet alert.
This is my HTML(which is using PHP in it).
<div class="delete"><a onclick="return confirmation()" href="'.URLROOT.'/dashboards/delete_note/'.htmlspecialchars($note->note_id).'/'.$data['table'] .'"><i class="far fa-trash-alt"></i></a></div>
This is my sweet alert
function confirmation() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
}
The problem is, its not showing the sweet alert, its just going straight to the URL. Do I need to do a form and prevent submits or something like that?

The problem is that click on anchor element has a default behavior. You could use event.preventDefault() to prevent the redirection and navigate manually based on you logic with window.location.href='url'
<div class="delete">
<a onclick="confirmation(event)" href="'.URLROOT.'/dashboards/delete_note/'.htmlspecialchars($note->note_id).'/'.$data['table'] .'">
<i class="far fa-trash-alt"></i>
</a>
</div>
and in js
function confirmation(ev) {
ev.preventDefault();
var urlToRedirect = ev.currentTarget.getAttribute('href'); //use currentTarget because the click may be on the nested i tag and not a tag causing the href to be empty
console.log(urlToRedirect); // verify if this is the right URL
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
// redirect with javascript here as per your logic after showing the alert using the urlToRedirect value
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});
}

You can add the value javascript: in the href attribute, like this
<a href = 'javascript:
swal({
title: "Delete selected item?",
text: "Unrecoverable Data",
icon: "warning",
buttons: true,
dangerMode: "true",
})
.then((willDelete) => {
if (willDelete) {
swal({ title: "Delete Data Successfully",
icon: "success"}).then(okay => {
if (okay) {
window.location.href = "";
}
});
} else {
swal({
title: "Data Not Deleted",
icon: "error",
});
}
});'
class = "btn btn-danger">Delete</a>

Try removing the href from the link and only handle the link when user click confirmed in the SweetAlert script.
<div class="delete"><a onclick="return confirmation()"><i class="far fa-trash-alt"></i></a></div>
In your javascript:
function confirmation() {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
// TODO: Handle your delete url by ajax
// ...
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});

Related

How to style the alert box on page refreshing before submitting the form

$(document).ready(function () {
$('form').submit(function(){
isSubmitting = true
})
$('form').data('initial-state', $('form').serialize());
$(window).on('beforeunload', function() {
return Swal.fire({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (!isSubmitting && $('form').serialize() != $('form').data('initial-state')){
Swal.fire("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
Swal.fire("Your imaginary file is safe!");
}
});
// return 'You have unsaved changes which will not be saved.'
}
);
});
I'm using above code to show alert on page refreshing.
How to show a customization styling alert box instead of default in react or is there any other way to show popup

How to show a popup alert in laravel

In my database i have a table called tasks and it has a column named file where files are stored. Now i want when a user click in the file he will show a pop-up message which ask either to download or view a file.
partially try like this
<a href="" id="popup">{{ $task->file }}
And i created a sweet-alert message for this like below
$(document).ready(function () {
$('popup').on('click', 'td.warning input', function () {
Swal.fire({
title: "Wow!",
text: "Message!",
type: "success",
showCancelButton: true,
cancelButtonText: "View",
confirmButtonText: 'Download!',
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
});
</script
Please help me to achieve this
Add some html code to the sweet alert, so you can show messages or images, something as i did here, you can see the documentation for more examples of what you can do:
https://sweetalert2.github.io/
<a href="" id="popup">{{ $task->file }}
<script>
$(document).ready(function () {
$('popup').on('click', 'td.warning input', function () {
Swal.fire({
title: "Wow!",
text: "Message!",
type: "success",
showCancelButton: true,
cancelButtonText: "View",
confirmButtonText: 'Download!',
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
});
</script>
Then you can add on sweet alert, some kind of messaging by adding on if and else swal's some of html code:
if (isConfirm) {
swal(
title:"Deleted!",
text: "Your imaginary file has been deleted!",
type: "success",
html: '<h1>Text here to download or to view</h1>'+
'<p>show some more text or show image</p>'
);
} else {
swal(
title:"Cancelled",
text: "Your imaginary file is safe :)",
type: "error",
html: '<h1>Text here to download or to view</h1>'+
'<p>show some more text or show image</p>'
);
}
Hope this works for you...

When I use Ajax sweet Alert doesn't show image. I'm working with laravel

When I use Ajax sweet Alert doesn't show image. I'm working with laravel.
This is my code, if I delete the ajax function or I use a image from another website it works.
I really have no clue, I think laravel need some kind of authetication from a Ajax request. Please help me out!
$(document).ready(function() {
$('.confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
warnBeforeRedirect(linkURL);
});
function warnBeforeRedirect(linkURL) {
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this team!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal({
title: "Checking...",
text: "Please wait",
icon: icons,
button: false,
allowOutsideClick: false
});
$.ajax({
url: linkURL,
type: 'GET',
success: function(result){
swal("The team was deleted!");
}
});
} else {
swal("The team was NOT deleted!");
}
});
}
});

Onclick Delete not stopping before pressing Okay

I am using an onclick on a delete call
"<a href='" + Url.Action("Delete", "OBProfile", new { id = "#= ProfileID#" })
+ "' title='Delete' id='deleteButton' class='btn btn-danger btn-sm
deleteButton' onclick='return confirm_delete(#= ProfileID#)'>Delete</a>"
and this is the script that it runs
function confirm_delete() {
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 () {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
});
};
The issue is that it doesn't stop and wait for the Delete button to be pressed. it calls the script, the box pops up, it deletes the record, and refreshes the page. I need it to process when I click the confirm button. This is done using SweetAlert
So, you anyway have to use jQuery for the swal to work. Therefore, do not use inline event handler like you did (onclick='return confirm_delete...). Use event binding the jQuery way, prevent the default behaviour, when delete is confirmed, set the location to go to the link URL as below.
$("#deleteButton").on("click", function(evt) {
evt.preventDefault();
var _this = this;
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) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
location.href = _this.href;
}
});
});
<link href="https://t4t5.github.io/sweetalert/dist/sweetalert.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://t4t5.github.io/sweetalert/dist/sweetalert-dev.js"></script>
<a href='http://www.aol.com' title='Delete' id='deleteButton' class='btn btn-danger btn-sm
deleteButton'>Delete</a>

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