Laravel ajax calls failing with response code 419

Recently I was working on a Laravel application with some ajax, and I was getting a 419 error after firing an Ajax call to a Laravel controller.

Laravel requires a token to be sent on some types of requests (POST being one of them), this is to prevent Cross site request forgery ( e.g. a form being submitted from somewhere it was intended by the developer to be submitted from ).

In php files its very easy to add this with the function call csrf_field().

But in js files, we need to essentially pull in this you store the token somewhere on the page and use js to pull it in.

            $.ajax({
                url: "/letutools/property/imagedelete",
                type: 'post',
                data: {
                    '_token': $('meta[name="csrf-token"]').attr('content'),                    
                    'name': 'name' /* other data */
                    
                    
                }
            });

you can pop the token in the page somewhere like this:

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

 

for reference: https://laravel.com/docs/5.5/csrf

 

 

 

 

Leave a Comment