I am trying to submit a form in laravel using ajax, which has some input types and upload file option. After submit a form, i got a error -
{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}exception: "Symfony\Component\HttpKernel\Exception\HttpException"file: "D:\development\laravel\parangatcrm\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"line: 389message: "CSRF token mismatch."
I have added this in my blade file -
<meta name="csrf-token" content="{{ csrf_token() }}">
<input type="hidden" name="csrf-token" value="{{ csrf_token() }}">
This is my ajax code -
$.ajax({
url: url,
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);
}
});
CodePudding user response:
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);
}
});