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

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.

Related

like/dislike button with api call not working using vue an mongoDB

I am learning vuejs and i am working on my first project which is a social network, and i want to implement a like button that call the api to add a like or remove it if the user has already liked it. It does work in my backend but i can't make it work in the front.
I need to send the userId and add or remove the like when i click on the button
This is the data
data() {
return {
post: {
file: "",
content: "",
likes: 0,
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
the last method i tried
likePost(id) {
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then(() => {
console.log("response", response);
this.user._id = response.data._id;
if(post.usersLiked == user._id) {
this.post.likes += 0
} else if (post.usersLiked != user._id) {
this.post.likes += 1
};
})
.catch((error) => console.log(error));
}
and this is the model
const postSchema = mongoose.Schema({
userId: { type: String, required: true, ref: "User" },
content: { type: String, required: true, trim: true },
imageUrl: { type: String, trim: true },
likes: { type: Number, default: 0 },
usersLiked: [{ type: String, ref: "User" }],
firstname: {type: String, required: true, trim: true },
lastname: {type: String, required: true, trim: true },
created_at: { type: Date},
updated_at: { type: Date }
});
Any idea what is wrong ? Thank you !
.then(() => { // you missed value response from Promise here
this.user._id = response.data._id;
if(post.usersLiked == user._id)
})
Do you mean this.post.usersLiked === user._id I suppose, so post within your data options should be
post: {
file: "",
content: "",
likes: 0,
usersLiked: false,
// something else reflect to your post schema
},
i want to implement a like button that call the api to add a like or remove it if the user has already liked it
By saying that you just need a simple boolean value to do this
likePost(id) {
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
// Just need to toggle state
this.$set(this.post, 'usersLiked', this.post.usersLiked !== response?.data?._id)
})
.catch((error) => console.log(error));
}
Found the answer, i changed the axios method to this
likePost(id) {
let userId = localStorage.getItem('userId');
axios
.post('http://127.0.0.1:3000/api/post/like/' + id, { userId }, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log(response.data);
this.getAllPost();
})
.catch((error) => console.log(error));
}
i also made a few changes to the data
data() {
return {
posts: [],
post: {
file: "",
content: "",
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
and i also made some changes on the controller
exports.ratePost = (req, res, next) => {
console.log(req.body.userId)
//using findOne function to find the post
Post.findOne({ _id: req.params.id }).then(post => {
if (!post.usersLiked.includes(req.body.userId)) {
// making a object with $inc and $push methods to add a like and to add the user's id
let toChange = {
$inc: { likes: +1 },
$push: { usersLiked: req.body.userId },
};
// we update the result for the like
Post.updateOne({ _id: req.params.id }, toChange)
// then we send the result and the message
.then(post =>
res
.status(200)
.json(
{ message: "Liked !", data: post }
)
)
.catch(error => res.status(400).json({ error }));
} else if (post.usersLiked.includes(req.body.userId)) {
// using the updateOne function to update the result
Post.updateOne(
{ _id: req.params.id },
// we use a pull method to take off a like
{ $pull: { usersLiked: req.body.userId }, $inc: { likes: -1 } }
)
.then(post => {
// then we send the result and the message
res
.status(200)
.json(
{ message: "Post unliked", data: post }
);
})
.catch(error => res.status(400).json({ error }));
}
});
};

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()".

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

How to properly catch errors in 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');
});