Laravel csrf token mismatch for ajax POST Request
You have to add data in your ajax request. I hope so it will be work.
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
Ajax Post to Laravel - CSRF Token Mismatch
I had the same problem
try to put include CSRF tag in your meta
like so
<meta name="csrf-token" content="{{ csrf_token() }}" />
and read it in your ajax code like so :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Last Update
Please modify your url variable like so :
jQuery.ajax({
type: "POST",
url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
data: data,
success: function() {
console.log("A");
}
});
Getting Error: CSRF token mismatch in laravel 8
You need to send the csrf token on header, not with the form data. try something like this on your code:
To add a default header with every request, use $.ajaxSetup():
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
or else you can add the header like below code:
$.ajax({
url: url,
headers: { 'X-CSRF-Token': ('meta[name="csrf-token"]').attr('content') }
type: 'PATCH',
data: new FormData($("#formId")[0]),
cache : false,
processData: false,
contentType: false,
success: function (res){
console.log(res);
}
,error: function (err){
console.log(err);
}
});
Regenerate CSRF Token If ajax request has an error
Remove headers from $.ajaxSetup and put it in send_form request like this.
$('#send_form').html('Sending..');
/* Submit form data using ajax*/
$.ajax({
url: "{{ route('register')}}",
method: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: $('#ajax-register-form').serialize(),
success: function(response) {
$('#send_form').html('Submit');
document.getElementById("ajax-register-form").reset();
},
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
$('.error-warning').show();
}
});
});
Related Topics
Recursive Function to Generate Multidimensional Array from Database Result
Best Way to Get Result Count Before Limit Was Applied
PHP Foreach Change Original Array Values
How to Evaluate Formula Passed as String in PHP
How to View Query Error in Pdo PHP
Simplest Two-Way Encryption Using PHP
How to Remove "Index.PHP" in Codeigniter'S Path
How to Create Multiple Where Clause Query Using Laravel Eloquent
How to Encrypt/Decrypt Data in PHP
Calling Closure Assigned to Object Property Directly
Startswith() and Endswith() Functions in PHP
PHP Regular Expressions: No Ending Delimiter '^' Found In
How to Convert Xml into Array in PHP
How to Send a Firebase Cloud Messaging Notification Without Use the Firebase Console