Cannot delete a row in Datatables after making it a delete request - php

I'm using DataTables in Laravel, and I want to delete a row from the database. It used to work when I did it as a get request in the route, but since I changed it to the delete request and put the csrf and method under the form, it stopped working. I receive - Data Not Deleted error. What can be a reason of that happening? Button that I receive from the index controller:
$button = ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="fas fa-fw fa-trash"></i> Delete</button>';
HTML form that appears when a delete button is clicked:
<div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="post" id="sample_form" class="form-horizontal">
#csrf
#method('DELETE')
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">Confirmation</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
</div>
</form>
</div>
</div>
</div>
Script:
var employee_id;
$(document).on('click', '.delete', function(){
employee_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function(){
$.ajax({
url:"/admin/employees/destroy/"+employee_id,
beforeSend:function(){
$('#ok_button').text('Deleting...');
},
success:function(data)
{
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Deleted');
}, 2000);
},
error: function(xhr, status, error) {
setTimeout(function(){
$('#confirmModal').modal('hide');
$('#employee_table').DataTable().ajax.reload();
alert('Data Not Deleted');
}, 2000);
},
})
});
});
Route:
Route::delete('/admin/employees/destroy/{id}', [EmployeeController::class, 'destroy']);
Controller function:
public function destroy($id)
{
$data = Employee::findOrFail($id);
$data->delete();
}

In your route you are using delete method, but in ajax call you have not mentioned the method, so the error is 405 method not allowed,
Try adding type: delete in ajax. something like this:
$.ajax({
type: 'DELETE',
url:"/admin/employees/destroy/"+employee_id,

To solve the problem I had to put csrf inside the meta:
<meta name="csrf-token" content="{{ csrf_token() }}" />
And use this at the beginning of the script:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>

Related

The GET method is not supported for this route. Supported methods: POST laravel on server

First of all sorry for my bad english. I've created a form that can update a data from a column using laravel and I created the form in a modal.
The Modal:
<!-- Modal -->
<div class="modal fade" id="edit_kesempatan_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Kesempatan</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST">
#csrf
{{ method_field('POST') }}
<div class="modal-body">
<input type="hidden" name="peserta-id" id="peserta-id">
<input type="hidden" name="ujian-id" id="ujian-id">
<input type="number" id="input_kesempatan" name="input_kesempatan" class="form-control" placeholder="Masukkan Kesempatan">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
but when I click the submit button the The GET method is not supported for this route. Supported methods: POST error occurs. I have checked the route and the javascript.
The Route:
Route::post('/cat_system/users/peserta/edit/status', 'AdminController#editStatusNew')->name('cat_system.peserta.ujian.edit.status');
Route::get('/cat_system/users/peserta/get-status', 'AdminController#getStatus')->name('cat_system.peserta.ujian.get.status');
The Js:
<script>
$(document).on('click', '.edit-kesempatan-button', function() {
var peserta_id = $(this).data('peserta-id');
var ujian_id = $(this).data('ujian-id');
var status = $(this).data('status');
$('#peserta-id').val(peserta_id);
$('#ujian-id').val(ujian_id);
$('#editForm').attr('action', '/cat_system/users/peserta/edit/status/');
$('#edit_kesempatan_modal').modal('show');
$.ajax({
url: '/cat_system/users/peserta/get-status',
type: 'GET',
data: { peserta_id: peserta_id,
ujian_id: ujian_id
},
success: function(data) {
$('#input_kesempatan').val(data.status);
}
});
});
</script>
the js is for submitting the form and the ajax is to get the status from the database and pass it to the value of the input.
the controller:
public function editStatusNew(Request $request)
{
$kesempatan = $request->input('input_kesempatan');
$peserta_id = $request->input('peserta-id');
$ujian_id = $request->input('ujian-id');
$affected = DB::table('peserta_ujian')
->where('peserta_id', $peserta_id)
->where('ujian_id', $ujian_id)
->first();
if(!$affected){
abort(404);
}
$update = DB::table('peserta_ujian')
->where('peserta_id', $peserta_id)
->where('ujian_id', $ujian_id)
->update(['status' => $kesempatan]);
return redirect('/cat_system/users/peserta')->with('success', 'Kesempatan updated successfully');
}
public function getStatus(Request $request)
{
$peserta_id = $request->query('peserta_id');
$ujian_id = $request->query('ujian_id');
$peserta_ujian = DB::table('peserta_ujian')->where('peserta_id', $peserta_id)->where('ujian_id', $ujian_id)->first();
return response()->json(['status' => $peserta_ujian->status]);
}
I have make sure that all the codes are the same in the server, but still the error occurs and the error only occurs on the server, It works fine on my local

How do I do a reset of the Bootstrap modal window without reloading the page ? Using PHP , jQuery, AJAX

I have a comment system. The user can report a bad comment (jquery and AJAX). When there are several comments for the same post the Bootstrap modal window retains the message from the previous report.
How do I do a reset of the modal window without reloading the page?
post.php
<button type="button" id="showModal" class="btn btn-primary btn-sm reporting" data-comment-id = "<?= $comment->getId() ?>" data-toggle="modal" data-target="#reportModal"></button>
<div class="modal fade" id="reportModal" tabindex="-1" role="dialog" aria-labelledby="title-report" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="title-report">Confirm reporting</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary submit-reporting">Validate</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
<input type="hidden" name="id" id="commentId" value="">
</div>
</div>
report.js
$(document).ready(function(){
$('.reporting').click(function(e) {
e.preventDefault();
$('#commentId').val($(this).data('comment-id'));
});
$('.submit-reporting').click(function(e) {
e.preventDefault();
var commentId = $('#commentId').val();
$.ajax({
url: 'post/moderateComment/' + commentId,
success: function(){
$(".modal-body").html("<p>The report has been forwarded!</p>");
$('.submit-reporting').attr("disabled", "disabled");
$('[data-comment-id = "'+commentId+'"]').hide();
}
});
});
});
I think what you are looking for is to have a modal with it's initial state? If that is so, you can do it by tweaking your modal when it is opened and resetting the elements that you want. So in your javascript, you should have something like:
$(document).ready(function(){
$('.reporting').click(function(e) {
e.preventDefault();
//Clean your message here*** with something like
//$('.elementWHereMessageIs').empty(); //Is faster than text('') or html('')
$(".modal-body").empty(); // I don't know if this is the message you want to empty?
$('#commentId').val($(this).data('comment-id'));
});
$('.submit-reporting').click(function(e) {
e.preventDefault();
var commentId = $('#commentId').val();
$.ajax({
url: 'post/moderateComment/' + commentId,
success: function(){
$(".modal-body").html("<p>The report has been forwarded!</p>");
$('.submit-reporting').attr("disabled", "disabled");
$('[data-comment-id = "'+commentId+'"]').hide();
}
});
});
});
Hope this helps!
Leo.

How to submit a remote modal form via ajax - jQuery

This is a little different from the method of submitting a form via static form value in modal. Using the same method is not working because AJAX not submitting the form value from the shown modal. So,
html
load form
modal
<div class="modal fade" id="xModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="xModalLabel">loading...</h4>
</div>
<div class="modal-body">...</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect">SAVE CHANGES</button>
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">CLOSE</button>
</div>
</div>
</div>
</div>
jquery
//clear modal
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
//submit form
$('#xModal').on('shown.bs.modal',function (e) {
e.preventDefault();
var form=$(this).find('form').serialize();
$('#save_btn').on('click',function(){
$.ajax({
url:'inc/data.php',
type:'POST',
data:form,
success : function(data){
console.log(data);
}
});
});
});
data.php
<?
print_r($_POST);
?>
remote_form.html
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="xModalLabel">Reg Form</h4>
</div>
<div class="modal-body">
<form>
<input type="text" name="fname" /><br />
<input type="text" name="lname" /><br />
<input type="text" name="email" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect" id="save_btn">SAVE</button>
</div>
</div>
Thanks, any comment is welcome!
Delegate your click event, move the event outside the on('shown.bs.modal') event
$(document).on('click', '#save_btn',function(){
var form=$(this).closest('form').serialize();
$.ajax({
url:'inc/data.php',
type:'POST',
data:form,
success : function(data){
console.log(data);
}
});
});
You can set ids to input fields and then getting data from that id as follows.
<input type="text" name="fname" id="fname"/>
and on the script do like this.
//submit form
$('#xModal').on('shown.bs.modal',function (e) {
e.preventDefault();
$('#save_btn').on('click',function(){
var fname = $("#fname");
$.ajax({
url:'inc/data.php',
type:'POST',
data:{
fname = fname
},
success : function(data){
console.log(data);
}
});
});
});

Passing data to a bootstrap modal from Laravel

Wonder if someone can help me with this one. I am a complete newbie with JS and JQuery.
I want to avoid accidents with deleting posts in my blog, so I want to have it so that when I hit delete it will pop up a modal to confirm I do want to delete the post and then do it or not.
I have added the following code.
<!-- Button trigger modal to delete post -->
<button type="button" class="btn btn-default btn-xs" data-toggle="modal" data-target="#deletePost">
Delete
</button>
<!-- Modal -->
<div class="modal fade" id="deletePost" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete Blog Post</h4>
</div>
<div class="modal-body">
<p>You are about to delete a blog post, are you sure all that effort is to be sent to the unrecoverable trash can?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">OMG, NO!!!</button>
<form action="/blog/{{ $post->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="pull-right btn btn-danger">Delete it!</button>
</form>
</div>
</div>
</div>
</div>
Now all that works fine, all I now want to do is that when I click the "delete it!" button it will do just that.
It all works apart from deleting the right post, I want to pass
{{ $post->id }}
to the modal so that it will send the post id to the controller.
My question is how I pass the id above to the modal? I have read a lot of examples and they are all so different so thought it better to get some views.
Thanks!
I would very much recommend using SweetAlert plugin, it is visually compatible with Twitter Bootstrap and much more pleasant to use.
This is a piece of code for multilingual, model-independant delete function:
$('body').on('click', 'sweet-delete', function (e) {
e.preventDefault();
var id = $(this).data('id');
var model = $(this).data('model');
swal({
title: lang.confirm_please,
text: lang.delete_warning,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: lang.delete_button,
closeOnConfirm: false,
showLoaderOnConfirm: true,
}, function(){
$.post('/'+model+'/'+id, {_method: 'DELETE'}, function(data){
swal({
title: lang.delete_title,
text: lang.delete_success,
type: "success",
timer: 5000
}, function(){
window.location.href = '/'+model;
});
});
});
})
And in you view:
<button data-id="{{$post->id}}" data-model="blog" class="pull-right btn btn-danger sweet-delete">#lang('app.delete')</button>
I have to mention that in order to attach CSRF token to my ajax forms I use:
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
in my app.js, and
<meta name="csrf-token" content="{{csrf_token()}}">
in my main layout file.
To pass the post ID to the modal form, it should be inserted in the modal using jQuery.
Button:
<button type="button" class="btn btn-default btn-xs delete-post" data-post-id="{{ $post->id }}">Delete</button>
Note: we will trigger the modal using the following, so we can also insert the ID.
jQuery:
$(document).ready(function() {
var modalObj = $('#deletePost');
$('.delete-post').click(function(e) {
var postId = $(this).data('post-id');
modalObj.find('form').attr('action', '/blog/' + postId);
modalObj.modal('show');
});
});
In this case, the action attribute is set dynamically, according to the relevant post id.

bootstrap handling a ajax form submission

I have been trying to get this form to load for a couple days now, but all I can get is the form to submit to a page (not what I want, I want the form to submit and then close the modal and then put a success message from news.php into the div "thanks" holder).
Can anyone spot the issue I am having where it will one load the "news.php" page?
<div id="thanks"></div>
<div class="modal fade" id="newsModal" tabindex="-1" role="dialog" aria-labelledby="newsModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="newsModalLabel">Add a News Post</h4>
</div>
<div class="modal-body">
<form class="addNew" role="form" method="POST" action="news.php">
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Enter title here...">
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="7" placeholder="Enter news post here..."></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="addNews">Add News Post</button>
</form>
</div>
</div>
</div>
</div>
and the javascript is:
<script type="text/javascript">
$(document).ready(function () {
$("button#addNews").click(function(){
$.ajax({
type: "POST",
url: "news.php",
data: $('form.addNew').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#newsModal").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
</script>
You didn't pass the event object to your click binding :
<script type="text/javascript">
$(document).ready(function (e) { // pass the event object
$("button#addNews").click(function(){
e.preventDefault(); // disable the POST of the form by the submit button
$.ajax({
type: "POST",
url: "news.php",
data: $('form.addNew').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#newsModal").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
Oops, I forgot the BootPly of my test.
I just replaced your POST request to a GET one, I don't know how to make POST request inside BootPly.
button#addNews is the submit button for the form, also it's click event is binded with an ajax call. When it is clicked, ajax process begins to execute while the form is being submitted.
You need to remove <form... start & end tags.

Categories