I've made a component in Vue.js 2.0 that delete's things with sweetalert. It looks like this:
export default {
props:['service', 'method', 'id'],
methods: {
destroy() {
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder',
cancelButtonText: 'Stop!',
confirmButtonColor: '#34495e',
cancelButtonColor: '#ff3860',
}).then (() => {
this.service[this.method](this.id)
.then(() => {
swal({
title: 'Verwijderd',
text: 'Succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 2000
});
location.reload();
})
.catch(() => {
swal({
title: 'Fout',
text: 'Heeft u voldoende rechten?',
type: 'error',
showConfirmButton: false,
timer: 2000
});
});
})
}
}
}
The problem is that this:
this.service[this.method](this.id)
Is not working. I'm passing the props like this:
<destroy :service="Service" method="destroy" :id="relation.id"></destroy>
The destroy method in the service class looks like this:
destroy(id) {
return axios.delete('/relaties/' + id);
}
In my vue debug bar the destroy component looks like this:
The error in my console:
Uncaught (in promise) TypeError: Cannot read property 'then' of undefined
at eval (eval at ./node_modules/babel-loader/lib/index.js?{"cacheDirectory":true,"presets":[["env",{"modules":false,"targets":{"browsers":["> 2%"],"uglify":true}}]]}!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./resources/assets/js/components/shared/Destroy.vue (app.js?id=d89bceb…:319), <anonymous>:27:54)
at <anonymous>
Any idea how I could fix this?
export default {
props:['service', 'method', 'id'],
methods: {
destroy() {
var self = this;
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder',
cancelButtonText: 'Stop!',
confirmButtonColor: '#34495e',
cancelButtonColor: '#ff3860',
}).then (() => {
self.service[self.method](self.id)
.then(() => {
swal({
title: 'Verwijderd',
text: 'Succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 2000
});
location.reload();
})
.catch(() => {
swal({
title: 'Fout',
text: 'Heeft u voldoende rechten?',
type: 'error',
showConfirmButton: false,
timer: 2000
});
});
})
}
}
}
You should create global link to "this" variable, in SWAL callback function "this" is replaced by local SWAL var.
Related
I wrote my code below and it works correctly and the answer is received correctly. But the problem is that when the confirm button is clicked, the sweetalert closes
I want the sweetalert not to be closed until the request is fully executed and the loading button to be displayed. I saw a lot of questions about this but they were related to ajax and I could not create them for livewire
document.addEventListener('DOMContentLoaded', function () {
$('.eg-swal-av3').on("click", function (e) {
Swal.fire({
title: 'title',
text: "content",
icon: 'info',
showCancelButton: true,
confirmButtonText: 'بله ایجاد کن',
cancelButtonText : 'لغو',
}).then(function (result) {
if (result.value) {
#this.call('createRequest');
}
});
e.preventDefault();
});
});
You're looking for the preConfirm property, which accepts a callback. This is where you would run the call to your createRequest.
I would also add a allowOutsideClick to be true when loading, so that the alert is visible throughout the request.
Swal.fire({
title: 'title',
text: "content",
icon: 'info',
showCancelButton: true,
confirmButtonText: 'بله ایجاد کن',
cancelButtonText : 'لغو',
allowOutsideClick: () => !Swal.isLoading(),
preConfirm: function(result) {
if (result) {
return #this.call('createRequest').then(() => {
Swal.fire('Loading complete');
});
}
},
});
I have an error in my sweetalert2 and I am using laravel vue in developing my app. What I want my app to happen is to create a confirmation modal for deleting a row in my database. Whenever I click "Yes", the item is removed but when I click the cancel button, the modal closes but also deletes the entire row. I am very confused as of the moment and this is my first time learning these frameworks and I want to learn more about this.
this is my code under the IndexComponent.vue
methods: {
deletePost(id) {
this.$swal({
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!',
closeOnCancel: true
}).then((result) => {
//send request to server
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts.splice(this.posts.indexOf(id), 1);
});
if (result.value) {
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
}
})
}
}
This is my button placed inside a td in my table:
<td><button #click="deletePost(post.id)" class="btn btn-danger">Delete</button></td>
This is what's inside my PostController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;
public function delete($id) {
$post=Post::find($id);
$post->delete();
return response()->json('Successfully deleted!');
}
All operations are working (CRUD) but when I tried to implement the sweetalert2 the deletions are multiple. Can someone please help me?
You have to write your API call inside if like this
methods: {
deletePost(id) {
this.$swal({
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!',
closeOnCancel: true
}).then((result) => {
//send request to server
if (result.value) {
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts.splice(this.posts.indexOf(id), 1);
});
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
}
})
}
}
Your splice index is incorrect. It will return -1, then it will delete the last item.
It should be
this.posts = this.posts.filter(post => post.id !== id)
Full code
methods: {
deletePost(id) {
this.$swal({
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!',
closeOnCancel: true
}).then((result) => {
//send request to server
if (result.value) {
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts = this.posts.filter(post => post.id !== id)
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
});
}
})
}
}
I am currently working with sweetalert2 and I am trying to detect when the alert closes. However the DeleteUnsavedImages function is not firing. I thought that assigning the function to the onclose key would work but no luck.
swal({
html: data,
showCloseButton: false,
showCancelButton: false,
width: 800,
showConfirmButton: false,
onClose: DeleteUnsavedImages()
}).then(function () {
});
function DeleteUnsavedImages(){
var test = "-1";
}
Any help would be appreciated :-)
I tested with my sweet alert to confirm the issue, you just need to pass the function name without () and the function will be called inside onClose event handler of swal. Its called passing a reference of the function to call when onClose gets fired of swal.
Make a little change like this:
swal({
html: data,
showCloseButton: false,
showCancelButton: false,
width: 800,
showConfirmButton: false,
onClose: DeleteUnsavedImages // Removed () from here
}).then(function () {
});
function DeleteUnsavedImages(){
var test = "-1";
}
swal({
html: data,
showCloseButton: false,
showCancelButton: false,
width: 800,
showConfirmButton: false,
onClose: () => {
this.DeleteUnsavedImages();
}
})
private DeleteUnsavedImages(){
}
swal({
title: "client",
content: html,
buttons:
{
cancel: {
text: "Close",
visible: true,
closeModal: true,
},
confirm: {
text: "Download",
visible: true,
closeModal: false
}
},
}).then((confirm) => {
if (confirm) {
download();
}
else {
DeleteUnsavedImages();
}
});
function DeleteUnsavedImages(){
var test = "-1";
}
I have ajax delete function but it keeps cannot work with my sweetalert,i dont know what wrong with my code,can't see any place wrong.Please tell me how to modify it.
function deletei(){
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!'
},function ($rfno,$user) {
theuser = $user;
therfno = $rfno;
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: $rfno, userid: $user},
success: function () {
swal('Deleted!', 'Your file has been deleted!', 'success')
}
});
});
}
<input type="button" value="button" onClick="deletei(\'' .$poarr[$i]['RefNo']. '\',\''.$poarr[$i]['StaffId'].'\')" >
So i have updated my successful answer for my current condition.Hope You guys can take a reference indeed,i did not add the library in fiddle ,so you guys may just copy this code and amend yourself.Thanks everyone who provide suggestion for me!
function deletei($refnos,$users){
var refId = $refnos;
var userId = $users;
SwalDelete(refId,userId);
e.preventDefault();
}
function SwalDelete(refId,userId){
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!',
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: refId, userid: userId},
success: function(data){
swal('Deleted!', 'Your file has been deleted!', 'success');
var tbl = document.getElementById("myTable");
for (var i=0; i < tbl.rows.length; i++) {
var trs = tbl.getElementsByTagName("tr")[i];
var cellVal=trs.cells[0].innerHTML;
if (cellVal=== refId) {
document.getElementById("myTable").deleteRow(i);
break; }
}
},
});
});
},
});
}
<button type="button" onClick="deletei(\'' .$poarr[$i]['RefNo']. '\',\''.$poarr[$i]['StaffId'].'\')" ></button>
showCancelButton: true, is deprecated. I will recommend using buttons. You could then create an array with what buttons you want.
function deletei(user,rfno){
var theuser = user;
var therfno = rfno;
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!'
},function () {
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: therfno, userid: theuser},
success: function () {
swal('Deleted!', 'Your file has been deleted!', 'success')
}
});
});
}
<input type="button" value="button" onClick="deletei(\'' .$poarr[$i]['RefNo']. '\',\''.$poarr[$i]['StaffId'].'\')" >
Try this .
Modification :- remove $ from $rfno
Edit:-You are not passing the value of username and regNo in deletei function.
You call deletei with the two arguments $poarr[$i]['RefNo'] and $poarr[$i]['StaffId'], but you don't use them in deletei. I suspect these arguments should be the value of theuser and therfno?
function deletei($rfno, $user){
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!'
}, function () {
$.ajax ({
type: "POST",
url: "updateleave.php",
data: {RefNo: $rfno, userid: $user},
success: function () {
swal('Deleted!', 'Your file has been deleted!', 'success')
}
});
});
}
I have a function on click for which I use sweetalert2. This is the function:
publish = function (article) {
swal({
title: "Skal du publisere?",
text: null,
type: "info",
showCancelButton: true,
cancelButtonText: "Avbyrt",
cancelButtonColor: '#FFF',
confirmButtonColor: "#2E112D",
confirmButtonText: "Ja, publisere"
}).then(function(){
var articleId = $(article).val();
$.post("/admin/articles/publish/article", {
'_token' : $('meta[name="csrf-token"]').attr('content'),
'articleId': articleId
}).done(function(){
$(article).hide();
return swal({
type: 'success',
title: 'Du har publisert den artikkel.',
showConfirmButton: false,
timer: 1000
});
}).fail(function() {
return swal({
type: 'warning',
title: 'Noeting gikk feil, prov igjen',
showConfirmButton: false,
timer: 1000
});
});
}, function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
}
Everything works fine but I get an error for the timer:
sweetalert2.min.js:1 Uncaught (in promise) timer
How can I avoid that, what am I doing wrong?
The problem is that you should generally never call a function that returns a promise without doing something with that promise. In this case the promise-returning functions are swal and $.post. If you ignore the returned promise then you're not waiting for it to complete. Your then handlers can return a promise to continue the promise chain, like this:
publish = function (article) {
return swal({
title: "Skal du publisere?",
text: null,
type: "info",
showCancelButton: true,
cancelButtonText: "Avbyrt",
cancelButtonColor: '#FFF',
confirmButtonColor: "#2E112D",
confirmButtonText: "Ja, publisere"
}).then(function(){
$(article).hide();
var articleId = $(article).val();
return $.post("/admin/articles/publish/article", {
'_token' : $('meta[name="csrf-token"]').attr('content'),
'articleId': articleId
}).then(function(){
return swal({
type: 'success',
title: 'Du har publisert den artikkel.',
showConfirmButton: false,
timer: 1000
}).catch(function(timeout) { });
});
}, function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
.catch(function(err) {
console.error(err);
throw err;
})
}
You need to add a rejection handler to the Promise. Alternatively, you can use .catch(swal.noop) as a quick way to simply suppress the errors:
swal('...')
.catch(swal.noop);
This issue is mentioned in the package documentation: https://github.com/limonte/sweetalert2#handling-dismissals
Also, there's the closed issue about the subject: limonte/sweetalert2#221