This is my button:
<button class="btn btn-danger" onclick="deleteConfirmation({{$wp->id}})" id="{{$wp->id}}" data-id="{{$wp->id}}"><i class="fa fa-trash"></i></button>
This is my jquery + ajax code:
function deleteConfirmation(id) {
swal.fire({
title: "Usunąć wypis?",
text: "Upewnij się czy chcesz usunąć ten wypis!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Tak, usuń go!",
cancelButtonText: "Nie, anuluj!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}/" + id,
data: {"_token": "{{ csrf_token() }}"},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Usunięto wypis!", results.message, "success");
} else {
swal.fire("Wystąpił błąd!", results.message, "error");
}
}.then(function() {
location.reload();
});
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
This is my Laravel Controller function destroy()
public function destroy(Request $request, $id)
{
//
$delete = \App\Wypisy::where('id', $id)->delete();
return back();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Wypis został usunięty !";
} else {
$success = true;
$message = "Wypisu nie znaleziono";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
return back();
}
when I click the button, show me the confirmation window, and when I click, remove it, I will receive the message jquery.min.js: 2 POST http://localhost:8000/przedsiebiorca/wypisy/3 404 (Not Found) does not happen. As I copy the link above, the removal method works correctly in Laravel. What am I doing wrong ? Any tips?
Laravel 5.8, jquery 3.4.1
If you are passing the id with POST
Your ajax function:
// code ...
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}",
data: {"_token": "{{ csrf_token() }}", "id": id},
dataType: 'JSON',
success: function (results) {
// code ...
Your route:
Route::post('/przedsiebiorca/wypisy/destroy', 'WypisyController#destroy');
Your Controller
public function destroy(Request $request)
{
//
$id = $request->id;
$delete = \App\Wypisy::where('id', $id)->delete();
// code ...
when i change my code for this
function deleteConfirmation(id) {
swal.fire({
title: "Usunąć wypis?",
text: "Upewnij się czy chcesz usunąć ten wypis!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Tak, usuń go!",
cancelButtonText: "Nie, anuluj!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/przedsiebiorca/wypisy/destroy')}}",
data: {"_token": "{{ csrf_token() }}", "id": id},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Usunięto wypis!", results.message, "success");
} else {
swal.fire("Wystąpił błąd!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
i recive in console:
jquery.min.js:2 POST http://localhost:8000/przedsiebiorca/wypisy/destroy
500 (Internal Server Error)
send # jquery.min.js:2
ajax # jquery.min.js:2
(anonymous) # (index):395
Promise.then (async)
ue.then # sweetalert.all.js:1
deleteConfirmation # (index):390
onclick # (index):173
Related
I am working with Laravel Datatable and I have stuck in one point. Below code for delete the entry in the TagManagement model. But it isn't delete the entry and worse thing is it didn't show any error. Can anybody find the error in below code?
view
$(document.body).on("click",".remove-tag", function () {
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
var tag_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Tag ?","deleteTag("+tag_id+")");
});
function deleteTag(id){
$.ajax({
type: 'get',
url: '{!! url('delete-tag') !!}',
data: {tag_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
Controller
public function destroy($id)
{
$tagManagement = TagManagement::find($id);
$deleted = $tagManagement->delete();
if ($deleted) {
return "SUCCESS";
} else {
return "FAIL";
}
}
public function loadTags()
{
$Tags = TagManagement::all();
return DataTables::of($Tags)
->addColumn('action', function ($tag) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $tag->id . '" class="btn btn-default remove-tag remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
}
**Route**
Route::get('/delete-tag', 'AdminPanel\TagController#destroy');
Your route and controller method don't seem to correspond. First of all, it is better to use the "delete" HTTP request method for delete actions, but this is not what is causing your problem.
You defined your route as /delete-tag but in your controller you expect an $id as a parameter to your destroy method. In order for that to work you would need to have the route like this /delete-tag/{id} and construct the URL for your ajax call correspondingly on the frontend. I'm surprised you don't get the Missing argument 1 for App\Providers\RouteServiceProvider::{closure}() exception for malforming your request this way.
Laravel documentation explains very well how to define routes with parameters.
It would be helpful if you included Laravel version in your question.
Here is how it should work:
Route definition
Route::delete('/delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('delete-tag');
JS function
function deleteTag(id){
let route = '{!! route('delete-tag', ['id' => '%id%']) !!}';
$.ajax({
type: 'post',
url: route.replace('%id%', id);,
data: {_method: 'delete'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
It is not your Datatable problem, you missed some code, you did not define route & jQuery function properly, your destroy($id) function received a parameter but you do not receive any parameter in your route & you not send _token in your ajax action you need to send _token
Check My code I am edited your code.
//Change your Route
Route::get('delete-tag/{id}', 'AdminPanel\TagController#destroy')->name('deleteTag');
//Change your function
function deleteTag(id){
$.ajax({
type: "GET",
dataType: 'JSON',
url:'{{ route('deleteTag', '') }}/'+id,
data: {_token: '{{csrf_token()}}'},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS","Delete Tag successful");
}
}, error: function (data) {
showAlert("FAIL","Delete Tag fail");
}
});
}
I want to delete records from a MySQL database table using AJAX. I have done it with PHP and work fine. But I've not been able to get it through with AJAX.
AJAX
$(document).ready(function() {
$(".confirm").click(function() {
var bid = $(this).closest("div.box2").find('input[name="dbid"]').val();
var dataString = 'id=' + bid;
$.ajax({
type: "POST",
url: "<?php echo site_url('user/delete_article')?>",
data: dataString,
cache: false,
success: function() {
$.alert('Confirmed!');
}
});
});
});
PHP
public function delete_article($id){
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->db->where('bid', $id);
$data['countEarticle'] = $this->db->count_all_results('blog');
if($data['countEarticle'] >= 1){
$this->db->where('bid',$id);
$this->db->delete('blog');
}
if($data['countEarticle'] <= 0){
}
}
HTML
<div class="box-footer box-comments box2" style="display: block;">
<input type="hidden" name="dbid" value="<?php echo $draftfull['bid']?>">
<p>
<btn class="btn btn-azure btn-sm confirm"><i class="fa fa-trash-o"></i>Delete Article</btn>
</p>
</div>
I need your help. What am I doing wrong?
try this code:-
public function delete_article(){
$id=$this->input->post('bid');
$data['success']='';
$data['error']='';
include_once ('query/user_query.php');
$this->db->where('bid', $id);
$data['countEarticle'] = $this->db->count_all_results('blog');
if($data['countEarticle'] >= 1){
$this->db->where('bid',$id);
$this->db->delete('blog');
}
if($data['countEarticle'] <= 0){
}
}
try this:
<span class="fa fa-ban"></span>
//ajax
function delete(id) {
swal({
title: "Are you sure to delete?",
text: "Deleting will remove row from listing!",
type: "error",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
cancelButtonText: "No",
closeOnConfirm: true,
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
$.post(
base_url + "user/delete_article",
{bid: id},
function (data) {
if (data === "1") {
location.reload();
} else if (data === "0") {
swal("", "Error to deleting data.", "warning");
} else {
swal("", data[0], "error");
}
});
}
});
}
//Controller
function delete_article($id){
if ( $this->model_name->deleteDataById($this->input->post('bid') ) {
die('1');
}
die('0');
}
I know there are similar questions relating to this issue, but I have tried my copy after those with the right answer, yet still to no avail.
I keep getting this error:
BadMethodCallException Method delete does not exist. in Macroable.php (line 74)
To be quick, here is my controller:
public function destroy(Subject $subject)
{
//
$response = array();
$modal = new Subject;
$modal = Subject::find($subject);
if ( $modal->delete() ) {
$response['success'] = '<b>'.$modal->name.'</b>'.' successfully deleted';
$response['subject'] = $modal;
}
return \Response::json($response);
}
Here is my route:
Route::delete('/subjects/delete/{subject}', 'SubjectsController#destroy');
Here is my view:
<td>
<a data-token="{{ csrf_token() }}" id="delete" data-id="{{$subject->id}}" data-toggle="tooltip" title="Edit" href="/subjects/{{$subject->id}}" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a>
</td>
and last my scripts:
$(document).on('click', '#delete', function(event) {
event.preventDefault();
/* Act on the event */
// id of the row to be deleted
var id = $(this).attr('data-id');
var token = $(this).data("token");
console.log(id);
// row to be deleted
var row = $(this).parent("td").parent("tr");
var message = "subject";
bootbox.dialog({
message: "Are you sure you want to Delete this "+message+"?",
title: "<i class='glyphicon glyphicon-trash'></i> Delete !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Delete!",
className: "btn-danger",
callback: function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/subjects/delete/'+id,
data: {
"id": id,
"_method": 'DELETE',
"_token": token
}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
}
}
}
});
});
Here is what I get when I don php artisan route:list
I don't know the technical details of why it is working this way but it seems the the problem was coming from my controller destroy method. So, this was all I had to do:
controller code:
public function destroy($subject)
{
//
$response = array();
$modal = new Subject;
$modal = Subject::find($subject);
if ( $modal->delete() ) {
$response['success'] = '<b>'.$modal->name.'</b>'.' successfully deleted';
$response['subject'] = $modal;
}
return \Response::json($response);
}
script:
callback: function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/subjects/delete/'+id,
data:{"id": id, "_method": 'DELETE'}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
}
route:
Route::delete('/subjects/delete/{subject}','SubjectsController#destroy');
The main thing for me was to remove the Subject from the destroy() parameter and it work.
If any of you know why it's working that please provide and explanation so that I can understand it too. Thanks!!
Change the type in your ajax call to POST, the _method field in the data object is all that is needed. This is how your ajax call should look. Laravel "fakes" the DELETE method by using the _method field to determine the http verb.
$.ajax({
type: 'POST',
url: '/subjects/delete/'+id,
data: {
"_method": 'DELETE',
"_token": token
}
})
.done(function(response){
bootbox.alert(response.success);
//removing the row that have been deleted
jQuery(row).fadeOut('slow');
})
.fail(function(){
bootbox.alert('Something Went Wrong .... Please contact administrator');
})
I have made a delete modal with Sweet Alert in Laravel and it is deleting user I choose. I would however after deletion like to redirect back to users list as my destroy() method says.
<script>
$('a#delete_user').on('click', function () {
var url = $(this).attr("data-href");
swal({
title: "Delete user?",
text: "Submit to delete",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete!"
},
function () {
setTimeout(function () {
$.ajax({
type: "POST",
url: url,
data: {
_method: 'DELETE',
_token: csrf_token
},
success: function (data) {
if (data)
swal("Deleted!", "User has been deleted", "success");
else
swal("cancelled", "User has not been deleted", "error");
}
}), 2000
});
});
})
</script>
Here is the controller:
public function destroy($id)
{
User::destroy($id);
return redirect('users')->with('status', 'User Deleted!');
}
I would like to redirect to users list with message, and I have trouble doing so
In your main template file or in view file, you have to check if there is status data in session, if yes so you call sweet alert. Example code:
#if (session('status'))
<script>
$( document ).ready(
swal("{{ session('status') }}")
});
</script>
#endif
Edit js file like this:
success: function (data) {
if (data == 'success')
swal("Deleted!", "User has been deleted", "success");
window.location('Your URL');
else
swal("cancelled", "User has not been deleted", "error");
}
and the controller:
if(User::destroy($id)){
return 'success';
}else{
return 'fail';
}
I'm trying to delete row from database with DELETE method and using AJAX in my Laravel 5.2 project. Everything is working, picture is deleted from server and the row is deleted from database but after deleting it redirects to JSON response.
My controller's action:
public function deletePhoto(Photo $photo)
{
if ($photo->delete()) {
unlink('files/' . $photo->filename);
unlink('files/thumbs/' . $photo->filename);
return response()->json(['result' => 0]);
}
return response()->json(['result' => 1]);
}
It works this way while adding photos (it adds but doesn't redirect).
Here is my ajax code:
$('#deleteForm').submit(function(e) {
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
I tried many changes (from laracast and stackoverflow) with method, token and data but nothing worked.
How do I solve this problem?
Add a prevent default to your submit event. The page is redirecting because you're initiating a submit event.
e.preventDefault();
Change submit event to:
$("#form-submit-button").click(function(e){
});
try this:
$('#deleteForm').submit(function(e) {
e.preventDefault()
var currentElement = $(this);
var formUrl = $(this).attr('action');
$.ajax({
type: 'POST',
url: formUrl,
data: {_method: 'delete', _token: '{{ csrf_token() }}'},
success: function(data) {
if (data.result == 0) {
currentElement.parent().fadeOut(400, function() {
$(this).remove();
});
} else {
alert('Wystąpił błąd podczas usuwania zdjęcia! Proszę spróbować ponownie!');
}
}
});
return false;
});
you need to add preventDefault to prevent the page from redirecting
check from console if there is errors in javascript code to work the e.preventDefault