I want to delete data from a database with an ajax call but it's showing an error.
CSRF token mismatch
In header:
<meta name="csrf-token" content="{{ csrf_token() }}">
In blade:
<button class="deletePhoto" data-id="{{ $photo->id }}" data-token="{{ csrf_token() }}">Delete</button>
AJAX call:
$('.deletePhoto').click(function () {
var id = $(this).data('id');
var el = this;
$.ajaxSetup({
headers:{
'X_CSRF_TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
},
success: function () {
$(el).closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
})
Controller:
public function destroy($id)
{
$photo = Photo::find($id);
$photo->delete();
}
This is what I usually do : [AJAX CALL]
$.ajax({
url: '/photo/delete/'+id,
type: 'DELETE',
dataType: 'JSON',
data:{
'id': id,
'_token': '{{ csrf_token() }}',
},
success: function () {
el.closest(".photo-details").remove();
console.log('DELETED');
},
error: function (xhr) {
console.log(xhr.responseText);
}
})
Related
I tried to solve this problem:
The GET method is not supported for this route. Supported methods:
POST.
But I can not find right way and error on Laravel 8.
Here is blade:
<a href="{{ route('operDel',$data->id) }}" class="btn btn-danger btn-sm"
data-tr="tr_{{$data->id}}"
data-id="{{$data->id}}"
data-toggle="confirmation"
data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn-sm btn-danger"
data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left"
data-btn-cancel-class="btn btn-sm btn-default"
data-title="Are you sure you want to delete ?"
data-placement="left" data-singleton="true">Delete</a>
And JavaScript in this blade
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success']) {
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
Here is Route
Route::delete('operDel/{id}', '\App\Http\Controllers\OperationController#destroy')->name('operDel')->middleware('auth');
And this is Controller
public function destroy($id)
{
Kvit::where('id', $$id)->delete();
return response()->json([
'success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id
]);
}
What I missed?
You need to pass method to the server.
$.ajax({
url: "operDel/"+id,
type: 'get',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function(data){
//do stuff
},
error: function(data){
//do stuff
}
);
Solved by this code
Blade
<button class="btn btn-icon btn-flat-danger deleteRecord"
data-id="{{$data->id}}">
<i class="fas fa-trash"></i>
</button>
JavaScript
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
if(confirm('Do you want to delete?')){
$.ajax(
{
url: "operDel/"+id,
type: 'post',
cache: false,
data: {
"id": id,
"method": 'post',
"_token": token,
},
dataType: "json",
success: function(response) {
if(response.status == "success"){
window.location.href='/operations';
}else if(response.status == "error"){
{toastr['error'](
'Please check datas..',
'You can not delete this!',
{
closeButton: true, tapToDismiss: true, progressBar: true,
}
);
}
}
},
});
}
});
I'm reaching Laravel 419 error while using Ajax and I don't have any idea about what is causing this.
I saw on other posts it has to do something with csrf token, but I have no form so I don't know how to fix this.
My code:
function check_login_auth(id) {
var email_address = $("input[name=l_email_address]").val();
var password = $("input[name=l_password]").val();
var token = $("meta[name=csrf-token]").attr("content");
$.ajax({
type: "POST",
url: baseurl+"route",
data: {
email:email_address,
password:password,
_token:token
},
dataType: 'json',
beforeSend: function() {
$('#l_loading_gif').show()
$('#l_login_form').hide()
},
success: function (data) {
// console.log(data)
},
});
} else {
$('#s_error').append('<p style="color: red">something went wrong.</p>')
}
}
Thanks you in advance!
You are calling POST method so You need to pass csrf_token in headers.
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
Your ajax looks like below.
$.ajax({
type: "POST",
url: baseurl+"route",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
email:email_address,
password:password,
_token:token
},
dataType: 'json',
beforeSend: function() {
$('#l_loading_gif').show()
$('#l_login_form').hide()
},
success: function (data) {
// console.log(data)
},
});
If you're calling it in js file then pass the csrf token in meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And headers like
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
First you have to get the csrf-token value in proper way
var CSRF_TOKEN = document.getElementById("csrf_token").value;
<input type="hidden" name="_token" id="csrf_token" value="{{ csrf_token() }}">
or
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
or
var CSRF_TOKEN = form.find("input[name='_token']").val();
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Then you have to pass this data in
data: {
email:email_address,
password:password,
_token: CSRF_TOKEN
},
When you are making post requests to laravel it expects a csrf token to protect your requests even if you do not use form. I suggest you to switch to axios since it is easily configurable.
with axios you can do something like this
axios.defaults.headers.common['X-CSRF-TOKEN'] = 'your token here';
axios.post('/url', {
firstName: 'something',
lastName: 'something'})
I am trying to delete image from folder using ajax and in route using delete method .In controller trying to delete image using image name in laravel.
Route:
Route::delete('remove-social/{filename}', 'Webadmin\Socials#removesocial');
Controller:
public function removesocial($filename){
File::delete('public/assets/uploads/Social/' . $filename);
}
View :
<a href="javascript:removesocialimage()" style="color: white;text-decoration: none;" class="btn btn-red">
<i class="glyphicon glyphicon-trash "></i> Remove</a> </label>
<script>
function removesocialimage() {
if (j('#file_name').val() != '')
if (confirm('Are you sure want to remove social icon?')) {
j('#loading').css('display', 'block');
var form_data = new FormData();
form_data.append('_method', 'DELETE');
form_data.append('_token', '{{csrf_token()}}');
j.ajax({
url: "remove-social/" + j('#file_name').val(),
data: form_data,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
j('#file_name').val('');
j('#loading').css('display', 'none');
},
error: function (xhr, status, error) {
alert(error);
alert(xhr.responseText);
}
});
}
}
</script>
Include this in your views head:
<meta name="csrf-token" content="{{ csrf_token() }}">
And do this ajax setup before making network calls:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
try to change route delete to post method
Route::post('remove-social/{filename}', 'Webadmin\Socials#removesocial');
if you want to used delete method then your ajax look like
add in head html tag
<meta name="csrf-token" content="{{ csrf_token() }}">
js code
j.ajax({
url: "remove-social/" + j('#file_name').val(),
data: form_data,
headers: {
X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'DELETE', //POST TO DELETE
contentType: false,
processData: false,
success: function (data) {
j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
j('#file_name').val('');
j('#loading').css('display', 'none');
},
error: function (xhr, status, error) {
alert(error);
alert(xhr.responseText);
}
});
i want to submit my form using ajax following is my javascript
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
url: "http://localhost/shago/register/submit",
data: user_firstname,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
i have included meta tag in form like
<div id="individual" class="hid">
<form method="POST" id="individual_form" name="individual_form" action="{{ route('register.submit') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
and in controller i have just returned a message but i am getting
POST http://localhost/shago/register/submit 419 (unknown status)
above error can you please help me ,let me know for any other inputs i know it is mostly caused by csrf token
(i have declared submit route in web.php and also api.php file)
Try this
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
url: "http://localhost/shago/register/submit",
data: {// change data to this object
_token : $('meta[name="csrf-token"]').attr('content'),
user_firstname:user_firstname
}
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
You can add below code to your master file
<script>
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
1) Use the meta tag in head section
<meta name="csrf-token" content="{{ csrf_token() }}">
2) Set header in ajax , like
header:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
3) Send CSRF token with data
data:({_token : $('meta[name="csrf-token"]').attr('content'),
name:name,category:category}),
or CSRF token can be written as
"_token": "{{ csrf_token() }}",
I have form to POST data to Controller and update database
The form in my orders.blade.php
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<select name="selectdb" required>
<option value="" disabled selected>Select Delivery Boy</option>
#foreach($delvery_boys as $delvery_boy)
<option name="selectdb" data-oid="{{$order->id}}" value="{{$delvery_boy->id}}">{{$delvery_boy->name}}</option>
#endforeach
</select>
<button type="submit" class="assigndb-btn btn-floating waves-effect waves-light">
<i class="material-icons">send</i>
</button>
</form>
I am doing an ajax POST request of form data to controller in my orders.blade.php
$(document).one("click", ".assigndb-btn", function () {
$('form').submit(function(event) {
event.preventDefault();
var order_id = $(this).find(":selected").data('oid');
var delivery_boy_id = $(this).find(":selected").val();
var delivery_boy_name = $(this).find(":selected").text();
$.ajax({
url: '{{ url('/manager/assign_orders') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And in my OrdersController.php i have the logic to updated the posted data
public function assignDeliveryBoy(Request $request)
{
$assign_delivery_boy = Order::where('id', $request->order_id)->update(['delivery_boy_id' => $request->delivery_boy_id]);
$data = [
'success' => true,
'message' => 'Order has been asigned'
];
return response()->json($data);
}
My Route is
Route::group(['prefix' => 'manager', 'middleware' => ['auth','roles'], 'roles' => 'manager'], function() {
Route::post('/assign_orders', 'OrdersController#assignDeliveryBoy')->name('assignOrder');
});
When i submit the form it suppose to hit the assign_order route and update the database
But in my console i am getting the html code of the page from where i submit the form basically it is executing GET instead of POST
As i checked in browser network whent the response is
Request URL:http://localhost:8000/manager/orders //but i am posting to http://localhost:8000/manager/assign_orders
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
i really don't understand what is wrong
thank you
Try this code.
$.ajax({
url: "{{ url('/manager/assign_orders') }}",
type: 'POST',
data:{
"order_id":order_id,
"delivery_boy_id":delivery_boy_id,
'_token':'{{ csrf_token() }}'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
Let me know if it works.
Try this:
$.ajax({
url: '{{ route('assignOrder') }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
$.ajax({
url: '{{ route("assignOrder") }}',
type: 'POST',
data: {"order_id":order_id,"delivery_boy_id":delivery_boy_id,'_token':'{{ csrf_token() }}'},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});