How to properly catch errors in SweetAlert - sweetalert

I have the following swal code and it works fine if the returned status for the HTTP call is '200'. But if I get a '403' unauthorized error the swal loader keeps spinning and the message never goes away, like shown below. I'm not sure if I'm not handling the error correctly.
Can you help?
let that = this;
swal({
title: 'Are you sure?',
text: 'You won\'t be able to revert this!',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
confirmButtonColor: '#d33',
cancelButtonText: 'No, keep it',
showLoaderOnConfirm: true,
preConfirm: function (email) {
return new Promise(function (resolve, reject) {
that.http.get(url, {"headers": headers})
.map(res => res)
.subscribe(data => {
console.log(data);
if (data.status === 200) {
resolve();
} else {
reject(data.status);
}
})
})
},
allowOutsideClick: false
}).then(function() {
swal(
'Deleted!',
'The user has been deleted.',
'success'
)
}, function(dismiss) {
if (dismiss === 'cancel') {
swal(
'Cancelled',
'Nothing has been deleted!',
'error'
)
}
}).catch((error) => {
console.log('error_does_not_reach_here', error);
})

This is a example of my code:
swal({
title: "Confirm",
text: "¿Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonText: 'Aceptar',
cancelButtonText: 'Cancelar'
}).then(function () {
//If Press ok, send the data
var arr = {
cuil: empDP.fd.Cuil,
cct: empDP.fd.Cct,
activity: empDP.fd.Activity,
};
Vue.http.post(empDP.globalurl + "/persondata/save", arr).then(function (response) {
swal('Data saved correctly', '', 'success');
empDP.clean();
}, function (response) {
//If Response return error
swal('Show a Text Error', '', 'error');
});

Related

Pass Validation Import Excel to Form using JSON/AJAX- Laravel

I try Laravel import excel using Maatweb. I want to 'handling error' using Javascript in my form. This is my code.
EmployeeImport
public function collection(Collection $rows)
{
Validator::make($rows->toArray(), [
'*.nik' => 'required',
'*.name' => 'required',
'*.id_department' => 'required',
'*.id_position' => 'required',
'*.id_group' => 'required',
'*.id_meet_point' => 'required',
])->validate();
foreach ($rows as $row) {
Employee::create([
'nik' => $row['nik'],
'name' => $row['name'],
'id_department' => $row['id_department'],
'id_position' => $row['id_position'],
'id_group' => $row['id_group'],
'id_meet_point' => $row['id_meet_point'],
]);
}
}
EmployeeController
public function import_excel(Request $request)
{
if($request->ajax()){
try {
$file = $request->file('file');
$nama_file = rand().$file->getClientOriginalName();
$file->move('file_employee', $nama_file);
Excel::import(new EmployeeImport, public_path('/file_employee/'.$nama_file));
return response()->json([
'status' => 200,
'message' => 'Berhasil di Import'
]);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
foreach($failures as $failure)
{
return response()->json([
'status' => 422,
'errors' => $failure->errors(),
]);
}
}
}
}
v_employee.blade
$("#importpost").on("submit", function(e) {
e.preventDefault();
var extension = $('#file_upload').val().split('.').pop().toLowerCase();
if ($.inArray(extension, ['csv', 'xls', 'xlsx']) == -1) {
alert('Please choose file csv/xls/xlsx!');
} else {
var file_data = $('#file_upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{route('employee.import')}}",
data: form_data,
type: 'POST',
contentType: false,
cache: false,
processData: false,
success: function(response) {
/* if (response.status == 442) {
$('#importform_errList').show();
$('#importform_errList').html('');
$('#importform_errList').addClass('alert alert-danger');
$('#importform_errList').append('<li>' + response.message + '</li>');
} */
console.log(response.status);
/* $('#importExcel').modal('hide');
tampil_table(); */
}
});
}
});
I have tried this code but still not show on my form for the validation. The error log still 422 (Unprocessable Content). Any help me ? What's wrong with my code?
I find other ways to showing validation error in my form.
So I changed my code like this.
$.ajax({
url: "{{route('employee.import')}}",
data: form_data,
type: 'POST',
contentType: false,
cache: false,
processData: false,
success: function(response) {
if (response.status == 200) {
Swal.fire({
icon: 'info',
title: 'Success',
text: 'Import File Berhasil',
showCancelButton: false,
showConfirmButton: true,
confirmButtonColor: '#fb3'
});
$('#importExcel').modal('hide');
tampil_table();
} else {
Swal.fire({
icon: 'error',
title: 'Failed',
text: 'Import Gagal. Silahkan cek table excel!',
confirmButtonColor: '#fb3',
showCancelButton: false,
showConfirmButton: true
});
}
},
error: function(data){
//console.log(data);
Swal.fire({
icon: 'error',
title: 'Failed',
text: 'Import Gagal. Silahkan cek table excel!',
confirmButtonColor: '#fb3',
showCancelButton: false,
showConfirmButton: true
});
}
});
I add error: function(), because validation define in this function. I just add error message with my custom word. Becase I don't know how showing up error(message) of the validation this function. I just share documentation.

How do i pass data to a function under data in vuejs

I tried to reference this.items in the function in taskList.cls.cls
the main idea is to run a task in vue-terminal then pass the result of the post request to this.items but it's returning undefined
data() {
return {
//this is the data i want to pass the post response to
items: [],
query: '',
taskList: {
// your tasks
cls: {
description: 'Clear Terminal',
cls: this, async(pushToList) {
const p = new Promise(resolve => {
this.query = 'SELECT * FROM notifications'
const token = localStorage.getItem('token')
axios.post('/query', {'query': this.query}, {
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
}).then(res => {
//i want to reference
**this.items = res.data.data.result**
//
pushToList({type: 'system', label: 'Running query', message: 'Please wait!!'})
}).catch(err => {
console.log(err)
})
setTimeout(() => {
resolve({type: 'success', label: 'Success', message: 'Success!'})
this.test = "worked"
}, 2000)
})
return p
}
}
},
commandList: {
// your commands
}
}
},
Don't do that, call api on "mount()".

RNFetchBlob.fs.writeFile how get notification on complete (NOT ALERT MESSAGE)

How to notifiy the user on success the file write.
RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
.then(res => {
console.log(res);
if (res > 0) {
alert('download_success');
} else {
alert('download_failed');
}
});
You can try using a local notification with react-native-push-notification
Here's how you can do it:
first of all, import the library
import PushNotification from 'react-native-push-notification'
and then, the function itself:
RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
.then(res => {
console.log(res);
if (res > 0) {
PushNotification.localNotification({
id: '69',
ticker: "Download sucess!",
autoCancel: true,
vibrate: true,
vibration: 300,
ongoing: false,
priority: "high",
visibility: "private",
importance: "high",
title: "My app name",
message: "Your file has now ben saved!"
});
} else {
PushNotification.localNotification({
id: '69',
ticker: "Download error!",
autoCancel: true,
vibrate: true,
vibration: 300,
ongoing: false,
priority: "high",
visibility: "private",
importance: "high",
title: "My app name",
message: "Errors ocurred while saving the file!"
});
}
});
RNFetchBlob.fs
.writeFile(pathToWrite, data, 'utf8')
.then(() => {
RNFetchBlob.android.addCompleteDownload({
title: 'data.pdf',
description: 'Download complete',
mime: 'application/pdf',
path: pathToWrite,
showNotification: true,
});
console.log(`wrote file ${pathToWrite}`);
})
.catch((error) => console.error(error));

I can't Integrat Sweet Alert After Axios Post action vueJs

i want to integrate this toast only if axios post is executed. i placed it like that and it's shown up even if my post axios function is not working.
how can i fix that ?
My code:
methods: {
addRinvoice: function () {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
}) },
Just put your call invoking the toast method inside your then() method:
methods: {
addRinvoice: function () {
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
})
},
place it inside then after getting response successfully like :
then(response=>{
...
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}
}

SweetAlert2 Cancel button not working properly

I have a Yes and No button in my SweetAlert2. When I click on No it does a post to a method but I just want it to close the SweetAlert.
Here is the code I have written:
$('.js-update-details-click').click(function () {
var Id = Number($(this).data('result-id'));
swal({
title: 'Are you sure you want to ask the User to update their details?',
type: 'warning',
showCancelButton: true,
closeOnConfirm: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No',
confirmButtonClass: 'btn btn-success btn-full-width mar-bot-5',
cancelButtonClass: 'btn btn-danger btn-full-width mar-bot-5',
buttonsStyling: false
})
.then(function (isconfirm) {
if (isconfirm) {
$.ajax({
type: "POST",
url: '/Common/ComposeUpdateDetailsEmail',
data: { ReplyType: 'CleanUpdateDetails', Id: Id },
success: function (data) {
swal('User has been sent an email to Update their Details.')
}
});
}
});
}
);
Most probably you updated the sweetalert2 dependency to ^7.0.0 and didn't read the release notes with breaking changes: https://github.com/sweetalert2/sweetalert2/releases/tag/v7.0.0
Starting from v7.0.0, SweetAlert2 will fulfill the promise for both confirm and cancel buttons and you need to handle the response from it this way:
Swal.fire({
...
}).then(function (result) {
if (result.value) {
// handle confirm
} else {
// handle cancel
}
})
Reference:
https://jsfiddle.net/ad3quksn/199/
`
swal({
title: 'Input something',
type: 'question',
input: 'text',
showCancelButton: true
}).then(
result => {
if (result.value) {
swal({
type: 'success',
html: 'You entered: <strong>' + result.value + '</strong>'
})
} else {
console.log(`dialog was dismissed by ${result.dismiss}`)
}
}
);
`
It shows with an output example of how to handle the promise as of v7.0.0: it helped me understand better!
Maybe help you :
swal("you liked it",{ buttons:{cancel:false,confirm:false}, timer:1000, })
ref : https://github.com/t4t5/sweetalert/issues/763