Ajax Laravel 419 Post Error

ajax 419 Error in Laravel

You havent included the CSRF token. The field is called csrf-token not _token and it needst to be contained in "" to be a valid selector.

$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});

Laravel 5.5 ajax call 419 (unknown status)

Use this in the head section:

<meta name="csrf-token" content="{{ csrf_token() }}">

and get the csrf token in ajax:

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Please refer Laravel Documentation csrf_token

What causes the 419 unknown status error in this Laravel 8 application?

set xmlhttp header for csrf token

function deleteAvatar(e) {
e.preventDefault();

var avatar = document.querySelector('#avatar-container img');
var topAvatar = document.querySelector('#top_avatar');
var trashIcon = e.currentTarget;
var defaultAvatar = APP_URL + '/images/avatars/default.png';

//Get user's ID
var id = trashIcon.dataset.uid;
var fileName = avatar.getAttribute('src').split('/').reverse()[0];

var url = APP_URL + `/dashboard/user/deleteavatar/${id}/${fileName}`;

if (confirm('Delete the avatar?')) {
var CSRF_TOKEN = document.querySelectorAll('meta[name="csrf-token"]')[0].getAttribute('content');

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
avatar.setAttribute('src', defaultAvatar);
topAvatar.setAttribute('src', defaultAvatar);
trashIcon.remove();
}
}
}

xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader("X-CSRF-TOKEN", CSRF_TOKEN);
xmlhttp.send();
}
}
document.querySelector('#delete-avatar').addEventListener('click', deleteAvatar);

Ref:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Ref: https://laravel.com/docs/9.x/csrf

Laravel 5.5 keep getting 419 post error on ajax call after several attempts

Add the meta tag with an id:

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

then on your ajax call:

     $.ajax({
url : "/getCompare",
type :"POST",
cash : false,
data: {'id': id, "_token": $('#token').val()},
type: 'POST',


success: function (response) {

},
error: function (response) {

}
});


Related Topics



Leave a reply



Submit