How to Deal With the CSRF Token While Using AJAX

The CSRF token can be problematic when using AJAX and I know I've had some trouble with it myself. In my example I will show you how to deal with it if you're using jQuery, but you should be able to easily adapt this to any JavaScript library or framework.

First of all, you shouldn't disable the CSRF protection just to get rid of this problem, because your application will become insecure.

How to use the CSRF token with AJAX

The easiest way to make sure you always have the CSRF token generated on any page where you're using AJAX is to include it in a meta tag and not a hidden input field, like it's usually done.

You can easily do this by including this in the head section of the pages where you're using AJAX.

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

Then you have to make sure that you send the token with any AJAX request. A very easy way to make sure you're always sending it is the jQuery code below. It will attach the X-CSRF-TOKEN header to any AJAX call.

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

By doing this you shouldn't worry about the CSRF token anymore.