hello i need help in laravel datatable, i get token in session but its not working, so how to pass in haeader in datatable ajax laravel, this is my working code. but its give me error Token is Required.
var token = localStorage.getItem('jwt_token');
console.log(token);
//$.fn.dataTable.ext.errMode = 'throw';
$('#kt_table_1').dataTable().fnDestroy();
$('#kt_table_1').DataTable({
processing: true,
serverSide: true,
dataType: 'JSON',
serverMethod: 'GET',
headers: {
'Authorization': token,
},
ajax: '{{route('api-product')}}',
columns: [
{
data : null,
"bSortable": false,
'render': function (data, type, row) {
return '<button type="button" data-id="' + data.id + '" id="edit" class="btn btn-primary" data-toggle="tooltip" title="" data-original-title="Quick Edit">Edit</button>\t\t\t\t\t\t<button type="button" data-id="' + data.id + '" id="delete" class="btn btn-danger" data-toggle="tooltip" title="" data-original-title="Quick Edit">Delete</button>';
}
},
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
]
});
I'm not sure your routes in the api.php or web.php. It is possible, it is asking for csrf_token. Please try passing token inside the object as
...DataTable({
data: {
"token": "{{ csrf_token() }}",
}
...
});
If you are using Oauth and want to pass in JWT barrier token then please refer this. https://laravel.com/docs/5.8/api-authentication#passing-tokens-in-requests
Apart from your solution I would recommend to use Axios https://github.com/axios/axios to fetch the data first and then populating into Datatable because of pagination issue you might face in future (depending on your needs).
Related
i wan to be able to dlete a price whereby upon clicking the delete button a modal appears which then shows the yes or no delete buttons.here is the ajax function in the view which contains the delete button
function removeogFuelPriceModel(id)
{
$.ajax({
url: "{{route('industryfuelprice.edit.modal')}}",
type: 'post',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
'id': id,
},
success: function (response) {
$("#showEditInventoryModal").html(response);
$("#showMsgModal").modal('show');
},
error: function (e) {
console.log('error', e);
}
});
}
here is a div inside the modal which contains the id which redirects to the delete ajax function
<div class="row"
style="width: 100%; padding-left: 0px; padding-right: 0px;">
<div class="col col-m-12 text-center">
<button type="button"
class="btn bg-primary primary-button"
**onclick="deleteData({{$oilgas->id}})"**
data-dismiss="modal">Yes</button>
<button type="button"
class="btn btn-danger primary-button"
data-dismiss="modal">No</button>
</div>
</div>
here is the ajax function in the modal
function deleteData(id) {
const url = "{{ route('industryoilgas.destroyFuelprice', ['model_id' => "MODEL_ID"]) }}".replace("MODEL_ID", id);
$.ajax({
url: url,
method: "POST",
enctype: 'multipart/form-data',
success: function (response) {
$("#showMsgModal").modal('hide')
$("#showEditInventoryModal").html(response)
$('#showMsgModal').modal('show');
$("#addFuelPrice").attr("disabled", false);
$("#addFuelPrice").css({"cursor":"pointer;"});
loadFuelPrice();
}, error: function (e) {
console.log(e.message)
}
});
}
here are my routes
Route::post('show-industry-fuel-price-edit-modal','IndustryOilGasController#showEditModalFuelPrice')->name('industryfuelprice.edit.modal');
Route::post('delete-fuel-price/{id}', 'IndustryOilGasController#destroyFuelprice')->name('industryoilgas.destroyFuelprice');
i don't understand why am getting that error
Make sure you have defined removeogFuelPriceModel() and deleteData() within a blade component, because an Laravel helper method cannot be resolved outside a predefined php file. In this case, you are mostly defining those methods inside a JS file which won't work properly. To address this issue, you may inject those methods inside a script layout within the blade component. I wish this could help you out!
I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()
i am new to Laravel and trying to find way to delete or add row with AJAX request.
Let's say i have PostController and i want to delete one of my post.
So in the PostController there will be destroy function :
public function destroy($id)
{
Posts::find($id)->delete();
}
Now, how i can send from a view AJAX Request to Controller and use this destroy method in secure way.
This works for me,
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>
OK, This works for me.
But the question is if this secure ?
AJAX Function
function removeRow(id){
token = $('#rmv').data("token");
console.log(id);
$.ajax(
{
url: "/posts/"+id,
type: 'POST',
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
$('#post'+id).remove();
}
});
}
VIEW
<a id="rmv" onclick="javascript:removeRow({{$post->id}})" data-token="{{ csrf_token() }}" class="btn btn-primary" >Delete</a>
I'm stuck in making a delete method using vue js and laravel. I tried to add a value to the href attribute using laravel resource and pass an id as a second parameter but when I click on it and display the id on console it shows the same id to all data which is incorrect.
Sample blade:
<a id="deleteRecord" data-id="{{$project->id}}" #click.prevent="deleteRecord" class="btn btn-circle btn-icon-only btn-danger" href="{{ route('projects.store', $project->id) }}">
<i class="icon-trash"></i>
</a>
Vue method:
deleteRecord: function(id) {
var dataId = $('#deleteRecord').attr('href')
console.log(dataId);
}
Inside of your method deleteRecord:
this.$http.delete(url)
.success(function(response) {
console.log(response)
})
.error(function(errors) {
console.log(error)
});
Or using axios inside of your method
axios.delete(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get it now. I'll just post it here to help others also.
deleteRecord: function(id) {
var url = "projects" + "/" + id;
$.ajax({
url: url,
type: 'DELETE',
data: { "_token": "{{ csrf_token() }}" },
success: function(response) {
//do some success stuff here..
}
});
}
I'm attempting to do a simple (soft) delete on my model from a customized implementation of the frozennode/administrator package. Whenever I hit my route via ajax, the application throws a TokenMismatchException.
I've tried with both cookie and file drivers set in the session config.
I have confirmed the _token is being submitted with the ajax request. Commenting the csrf filter out altogether allows me to successfully delete the record. I'm using the out-of-the-box csrf filter.
I'm also using the excellent Sweet Alert plugin, though that doesn't appear to be related.
routes.php:
//CSRF protection in forms
Route::group(array('before' => 'csrf'), function()
{
//Delete Item
Route::post('{model}/{id}/delete', array(
'as' => 'admin_delete_item',
'uses' => 'Frozennode\Administrator\AdminController#delete'
));
...
Blade template:
<a href="" class="btn btn-danger" id="delete-item-button" data-token="{{ csrf_token()}} ">
<i class="fa fa-trash"></i>
<span>
Delete
</span>
</a>
Javascript:
Excuse my hellishness $.post is what's relevant.
$('#delete-item-button').on('click', function (e) {
e.preventDefault();
var token = $(this).data('token');
swal({
title: "Delete this record?",
text: "There's no undo!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function () {
$.post(
window.location.pathname + "/delete",
{"_token" : token},
function(){
swal({
title: "Deleted!",
text: "The record has been deleted.",
type: "success"
},
function () {
window.location.href = 'http://www.example.com'
})},
"json"
);
});
});
Any help or guidance would be greatly appreciated.
Thanks!