jQuery add CSRF token to all $.post() requests’ data

From Laravel documentation:

You could, for example, store the token in a “meta” tag:

Once you have created the meta tag, you can instruct a library like
jQuery to add the token to all request headers. This provides simple,
convenient CSRF protection for your AJAX based applications:

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

So for example you can do request like below.

Add this meta tag to your view:

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

And this is an example script which you can communicate with Laravel (sends request when you click an element with id=”some-id” and you can see the response in an element with id=”result”):

<script type="text/javascript">
    $(document).ready(function(){

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

        $("#some-id").on("click", function () {
            var request;


            request = $.ajax({
                url: "/your/url",
                method: "POST",
                data:
                {
                    a: 'something',
                    b: 'something else',
                },
                datatype: "json"
            });

            request.done(function(msg) {
                $("#result").html(msg);
            });

            request.fail(function(jqXHR, textStatus) {
                $("#result").html("Request failed: " + textStatus);
            });
        });

    });
</script>

Leave a Comment