我正在尝试在laravel应用中使用sweetalert.js,并将其用于删除按钮,问题是我使用OK
按钮还是CANCEL
按钮删除了我的数据。 / p>
Button
我要在表单中添加'onsubmit' => 'return ConfirmDelete()'
。
{!! Form::open(['method' => 'DELETE', 'route' => ['attribute-groups.destroy', $attribute->id],'onsubmit' => 'return ConfirmDelete()' ]) !!}
<button data-toggle="tooltip" data-placement="left" title="Delete" class="btn btn-danger btn-rounded btn-sm" type="submit"><span class="fas fa-times"></span></button>
{!! Form::close() !!}
JavaScript
<script>
function ConfirmDelete(){
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this group or it's values!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your group file has been deleted!", {
icon: "success",
});
} else {
swal("Your group file is safe!");
}
});
}
</script>
PS:
如果我使用简单的东西
<script>
function ConfirmDelete(){
return confirm('Are you sure?');
}
</script>
OK
和CANCEL
按钮可以很好地工作,但是看起来甜蜜的警报需要更多的工作来完成。
有什么想法吗?
基于Mozammil
,这是我现在所拥有的:
delete form
{!! Form::open(['method' => 'DELETE', 'route' => ['attribute-groups.destroy', $attribute->id]]) !!}
<button data-toggle="tooltip" data-placement="left" title="Delete" class="del btn btn-danger btn-rounded btn-sm" type="submit"><span class="fas fa-times"></span></button>
{!! Form::close() !!}
js
<script>
$(document).ready(function(){
$('.del').click(function(e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this group or it's values!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: $(this).closest('form').attr('action'),
type: 'DELETE',
success: function(result) {
swal("Poof! Your group file has been deleted!", {
icon: "success",
});
}
});
} else {
swal("Your group file is safe!");
}
});
});
});
</script>
问题
现在,CANCEL
按钮将取消活动,而OK
按钮也将充当取消按钮。
两个都取消。
controller function
public function destroy($id)
{
$attribute = AttributeGroup::findOrFail($id);
$values = Attribute::where('attribute_id',$attribute->id)->get();
foreach($values as $value){
$value->delete();
}
$attribute->delete();
Session::flash('success', 'Attribute Group Deleted Successfully.');
return redirect()->route('attribute-groups.index');
}
PS:单击确定,添加后,我的网络标签中出现419
错误
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
但是我遇到相同的错误419
答案 0 :(得分:2)
这是一个非常简单的示例,说明如何使它起作用。
$('#btnDelete').click(function(e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this group or it's values!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: "{{ route('attribute-groups.destroy', ['id' => $attribute->id]) }}",
type: 'DELETE',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(result) {
// reloads the page..
location.reload();
}
});
} else {
swal("Your group file is safe!");
}
});
});