I want to integrate sweetalert with my project. but I'm having the following error.
this is my html code
<script type="text/javascript">
$('.bank').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: 'btn btn-success',
cancelButton: 'btn btn-danger'
},
buttonsStyling: false,
})
swalWithBootstrapButtons.fire({
title: 'Are you sure?',
text: "Payment method Bank Transfer Mandiri!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes!',
cancelButtonText: 'No, cancel!',
reverseButtons: true
},
function(isConfirm) {
if (isConfirm){
$('#my-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "{{ route('payment') }}",
data: $('#my-form').serialize(),
success: function (data) {
//
}
});
});
}
});
});
</script>
I've been looking for solutions to this problem quite a long time, but I still can not solve it
please help me. thx..
Please include the CDN available for sweatalert.js .
As I don't see any erros above,
I suggest you to add the following code before script .
https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js
Related
Hello guys I'M having an issue with my sweetalert delete confirmation. When I click on "Yes Delete it!" nothing happens and there are no errors showing in my console please guys I seriously need help this has kept me on deck for a long time now. I really be grateful if I get quick responses.
This is my blade.php
<button onclick="deleteConfirmation({{$poster->id}})" type="button" class="btn btn-danger delete-confirm offset-md-2">Delete</button>
<script type="text/javascript">
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Are you sure you want to delete this?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: true
}).then(function (e) {
if (e.value) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'DELETE',
url: "{{ url('delete-post') }}" + '/' + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
And here is my controller
public function deletepost($id)
{
dd($id);
DB::table('posters')->where('id', $id)->delete();
return back()-> with('post_add', 'Post deleted Successfully');
}
And my route
Route::delete ("/delete-post/{id}", [PosterController::class, "deletepost"])->name("poster.delete");
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.
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!");
}
});
}
});
I wanted to pause form's onsubmit, so I could ask user to confirm action before proceed.
So here's my form:
<form action="<%= request.getContextPath()%>/Controller"
method="POST" id="remove_book"
onsubmit="alertBookInfo('return_book')">
</form>
Then, I created the JavaScript function, using SweetAlert:
function alertInfo(action) {
document.querySelector(action).addEventListener('submit', function (e) {
var form = this;
e.preventDefault();
if (action === "remove_book") {
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function () {
form.submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
});
}
But for some reason, I am unable to prevent page reload on form submit. Am I doing someting wrong?
PS: I already tried with return alertInfo() in form and returning boolean value from JS function with no success.
Why not call the function from the form like this, the the alert will be prompt before submitting the form:
HTML
<form action="<%= request.getContextPath()%>/Controller" method="GET" id="remove_book" onclick="myAlertFunction(event)">
<input type="submit">
</form>
JavaScript
function myAlertFunction(event) {
event.preventDefault()
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function() {
$("#remove_book").submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
And if you want to prevent the reload, you can always use event.preventDefault()
Here is an example: JSFiddel
If you don't want the page reloads you could use an AJAX call. When you use the submit() you will always reload the page because is how submit works.
$.ajax({
method: "POST",
url: YOUR_ACTION_URL,
data: $('form').serialize(),
success: function(data){
//here you could add swal to give feedback to the user
}
});
In your controller you have to define the method as produces JSON, if you are using Spring, the annotation is #ResponseBody
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>