php - Laravel 419 Error - VerifyCsrfToken issue when using Ajax

Solution:

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')
}

Answer

Solution:

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

Answer

Solution:

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
    },

Answer

Solution:

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'})

Source