Reputation: 5608
I am requesting POST
:
Route :
Route::post('/register','CommonController@postRegister')->name('register');
CSRF Meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
$("#submitSalonForm").click(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/register",
type: "post",
data: new FormData($('form')[1]),
cache: false,
contentType: false,
processData: false,
success:function(response) {
return alert('Form 2 submitted');
}
});
});
And the exception :
The exception comes sometimes and sometimes the code runs smoothly, I have no idea what am i missing here.
Upvotes: 2
Views: 13873
Reputation: 300
In addition to putting the crsf-token value in the header meta tag you need to pass it through in your AJAX requests like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Upvotes: 2
Reputation: 64
Well, I know I am too late, but I did face the exact issue you face.
I was 100% sure that the token has been sent with the request, but the issue is still.
So, after too many searches I finally got it fixed by following these steps:
php artisan config:clear
php artisan view:clear
php artisan route:clear
php artisan cache:clear
php artisan clear-compiled
Upvotes: 0
Reputation: 5609
No need to setup ajax separately. Laravel automatically generates a CSRF "token" for each active user session managed by the application. Get the token with this:
var token = "{{ csrf_token() }}";
Pass the token in data
var token = "{{ csrf_token() }}";
var formData = new FormData($('form')[1])
$.ajax({
url : '/register',
data : {_token:token,formData:formData},
type: 'post',
...
})
Upvotes: 0
Reputation: 7420
Change ajax method from post to get
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Ajx call:
let formData = $('form').serializeArray();
$.ajax({
url: "/register",
type: "POST",
data: {formData, "_token": $('#token').val()},
cache: false,
datatype: 'JSON',
processData: false,
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
Your route is get
Route::get('/register','CommonController@showRegister')->name('register');
Ajax call is making a post request, laravel sqwaks with a http exception.
EDIT: Laravel 419 post error is usually related with api.php and token authorization
So try to include the token on ajax body instead like above.
Upvotes: 4