Laravel 4 AJAX CSRF Token Mismatch (with _token) - laravel-4

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!

Related

Vue js Laravel Sweet Alert Form Submit on confirm

I have a form in Laravel /VueJS with multiple submit buttons. I wrote a code for confirm on submit with input button.
After Sweet Alert confirm, the form does not get submitted, as there is event.preventDefault().
Can anyone help me on what I need to do ?
<template>
<div class="large-12 medium-12 small-12 cell">
<input type="submit" name="submit" v-on:click="showAlertConfirm()"></input>
</div>
</template>
<script>
export default {
methods: {
showAlert(){
this.$swal('Hello Vue world Test!!!');
},
showAlertConfirm()
{
event.preventDefault();
var form = $('input[name="submit"]').closest("form");
console.log('form');
console.log(form);
this.$swal.fire({
title: 'Are you sure you want to submit?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes'
}).then((result) => {
console.log(result);
if (result.isConfirmed==true) {
//this does not work
form.submit();
this.$swal.fire(
'Submitted!',
'Your file has been submitted.',
'success')
}
})
},
}
}
</script>

How to pass jwt token in ajax datatable header laravel

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).

Confirm Before Deleting with Sweet Alert Laravel 5.5

I want the sweet alert box to go out without deleting.
But id not found for ajax
Route
Route::get('room/delete/{id}', 'RoomList#destroy')->name('roomdelete');
View File rooms-list.blade.php
#foreach($rooms as $room)
<tr>
<td>{!! $room->room_id !!}</td>
<td>{!! $room->hotel_id !!}</td>
<td>{!! $room->room_name !!}</td>
<td>
<i class="fa fa-close text-danger"></i> </td>
</tr>
#endforeach
SweetAlert Js Code above
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('room/delete')}}",
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Controller File RoomList.php
public function destroy($id) {
$rooms = Room::find($id);
$rooms->delete();
return redirect()->back()->with('deleted', 'Delete Success!');
}
Clicking on the delete button does not work
Best Regards
First thing first, you have a GET route and you are sending a POST request here so first change your ajax method to GET like this:
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "GET",
url: "{{url('room/delete/')}}+id", // since your route has /{id}
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Also I'm not sure about $(document).on('click', '.button', function (e) I guess it should be like this:
$('.button').on('click', '.button', function (e)
Let me know If you still have any issue.

how to use pjax and sweetalert confirmation to delete row in laravel 5.3

I use sweetalert to get confirm for delete rows from user, the code for confirmation is
$('.delete').click(function(){
var formClass = $(this).attr('id');
$("form."+ formClass).submit(function( event ){
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
}, function() {
form.submit();
});
} else {
swal("Cansel", "Not deleted :)", "error");
}
});
});
});
and this code for use pjax to have an ajax request in laravel
$(document).on('pjax:send', function() {
$('#loading').show();
$("#pjax-container").css({"opacity": "0.3"});
})
$(document).on('pjax:complete', function() {
$('#loading').hide();
$("#pjax-container").css({"opacity": "1"});
})
$(document).on('submit', 'form[form-pjax]', function(event) {
$.pjax.submit(event, '#pjax-container')
});
And the html form is:
<form action="{{ route('admin.comments.destroy',[$comment->id]) }}" class="inline-div comment-{{ $comment->id }}" method="post" form-pjax>
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-danger btn-opt delete" id="comment-{{ $comment->id }}"><span class="glyphicon glyphicon-trash"></span></button>
By this code i haven't an ajax request.
Instead of "form.submit();" What to write?
From what I can see, you don't need to use pjax for this at all. You can delete a record from database asynchronously, simply using an ajax request. Here is how I would go about doing this:
In the code below, when the user clicks on the delete link, an alert would be presented to him. If he confirms the delete action, then the function deleteFromDB would be called which is responsible for sending an ajax request to the server.
$('.delete').click(function(){
var formClass = $(this).attr('id');
event.preventDefault();
swal({
title: "Do you want delete this item?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: "No",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
deleteFromDB(formClass);
} else {
swal("Cancel", "Not deleted", "error");
}
});
});
The mentioned function is defined as below:
function deleteFromDB(formClass) {
var url = "http://example.com/delete/this/record";
var form = $("form."+ formClass);
var formData = new FormData();
form.find("input[name]").each(function(index, input) {
formData.append(input.name, input.value);
});
$.post(url, formData).done(function(data) {
swal({
title: 'Deleted!',
text: 'the item is deleted!',
type: 'success'
});
});
}
It finds all the inputs that have a name attribute and appends each to a FormData object. Then a post ajax request is sent to the server and when the request is done, another alert showing the success of deletion shows up.
Pay attention here not to show the success alert before deleting the record (as you were doing in the above code), because then if something goes wrong during the request, i.e. the record could not be deleted for some reason, you would be able to show that error to the user.

Ajax post internal server error in codeigniter

I am new in ajax . I try to save data in database in Codeigniter framework using ajax.
This is my ajax code:
$('#cmpNameEditForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: '<?=base_url();?>company/home/updateName',
type: 'POST',
data: {
'name': $('#cmpName').val(),
},
success: function(data) {
$('p.error').html(data);
}
});
});
My view page is:-
<div id="name-edit-clone">
<?=form_open_multipart('', array('name'=>'CmpNameEditForm', 'role'=>'form', 'id'=>'cmpNameEditForm'))?>
<h3>Company Name</h3>
<?=form_input(array('name'=>'cmpName', 'id'=>'cmpName', 'placeholder'=>'Company Name', 'value'=>$company_name));?>
<?php echo form_error('cmpName','<p class="error">','</p>'); ?>
<?=form_submit(array('name'=>'submit', 'value'=>'Save', 'class'=>'btn btn-success nameSave'));?>
<?=form_button(array('name'=>'button', 'type'=>'reset', 'content'=>'Cancel' , 'class'=>'btn btn-danger nameCancel', 'id'=>'cmp-name-hide'));?>
<?=form_close()?>
</div>
What i am in wrong. Please help. Thanks you.

Resources