DELETE not working in the Laravel Datatable - php

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");
}
});
}

Related

set name to widget's attribute in Twig

I have a field (called name), Every time i write in this field, an ajax script (live search sends data from twig to the controller without reloading) checks if the data already exist or not showing a message. My problem is that i could't set a name for this field, i tried this but it does not work
{{ form_label(form.name) }}
{{ form_widget(form.name,{'id':'name','attr':{'name':'name'}}) }}
{{ form_errors(form.name) }}
and here my function in the controller which i'm sure it works properly,
public function searchBackTeamAction(Request $request)
{
if($request->isXmlHttpRequest())
{
$serializer = new Serializer(array(new ObjectNormalizer()));
$em = $this->getDoctrine()->getManager();
$teams= $em->getRepository('TeamBundle:Team')->findOneBy(['name'=>$request->get('name') ]);
$data = $serializer->normalize($teams);
return new JsonResponse($data);
}
}
and here is my script i'm also sure that it works properly
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: $("#name").serialize(),
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);
</script>
Could you please help me ?
Use following javascript
<script>
$(document).ready(function () {
$("#name").keyup(
function(){
$.ajax({
url: "{{ path('team_searchBack') }}",
data: {"name": $("#name").val()},
type:"POST",
success: function (data, status, object) {
console.log(data);
if(data.name != null)
{
$("#error_login").css('display','block');
$("#submit").prop('disabled', true);
}
else
{
$("#error_login").css('display','none');
$("#submit").prop('disabled', false);
}
},
error: function(req, textStatus, errorThrown,data) {
//this is going to happen when you send something different from a 200 OK HTTP
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
})
}
);

How to delete record in laravel via ajax

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');
})

Ajax DELETE redirects even if prevented

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

CodeIgniter: Delete data from MySQL DB using AJAX

I am working on a project, where inside admin panel I have a table for enquiries and I want to allow admin to delete any of them.
My view code is as follows:
<button type="button" class="btn btn-danger delbtn" onclick="delenquiry(<?php echo $value->id;?>)">Delete this Enquiry</button>
My ajax code is:
function delenquiry(id) {
if (confirm("Are you sure?")) {
$.ajax({
url: base_url + 'loginc/delenq',
type: 'post',
data: id,
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
} else {
alert(id + " not deleted");
}
}
Controller code is:
public function delenq() {
$id = $this->input->post('id');
$this->logins->delenqs($id);
}
And model code is:
public function delenqs($id) {
$this->db->where('id', $id);
$this->db->delete('enquiry');
}
I looked for answers, but didn't got any. Can anyone tell me what's wrong with my code. Thanks in advance...
You need to pass id from your ajax request change
data: id,
To
data: {id:id},
for data you must provide an array .
for example => data:{name_params:10}
you can get data in php $id = $this->input->post('name_params');
and the value $id will be = 10
The issue you have is that your ID is not an available key in your POST. You would need to define {id : id}. However, I think this makes more sense from an MVC approach:
$.ajax({
url: base_url + 'loginc/delenq/'+ id, //maintains the (controller/function/argument) logic in the MVC pattern
type: 'post',
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a,b,c);
}
});
Then you can expect an argument to your controller function:
public function delenq($id){
if($id)
return $this->logins->delenqs($id);
return false;
}
And finally, your model can get a little fixer upper so that it properly returns as well.
public function delenqs($id) {
$this->db->delete('enquiry', array('id' => $id));
return $this->db->affected_rows() > 1 ? true:false;
}

Get a single row from the database using AJAX in CodeIgniter?

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.

Categories