Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DavidPowersOG's avatar

Ajax (jQuery) & CSRF

I'm using the following code to inject the csrf token for jQuery requests, after embedding it into the page metadata, but I wonder if there is a better way? This method just seems wrong to me for some reason...

$.ajaxPrefilter(function(options, originalOptions, xhr) { 
    var token = $('meta[name="csrf-token"]').attr('content'); 
    if (token) {
        return xhr.setRequestHeader('X-CSRF-TOKEN', token); 
    }
});
0 likes
8 replies
davielee's avatar

There is really only two ways essentially. What you've done there and by just adding it via a script tag.

<script>
    var Laravel = {
        csrf: "{{ csrf_token() }}"
    };
</script>
<script>
$.ajaxPrefilter(function (options, originalOptions, xhr) {
    var token = Laravel.csrf;

    if (token) {
        return xhr.setRequestHeader('X-CSRF-TOKEN', token);
    }
});
</script>

Both are so miniscule in terms of performance it really doesn't make a difference. Your way shown you have to make a DOM query, this way has to add another script tag. It's really up to you how you want to do it.

Edit: Exactly what @SaeedPrez said.

adeptsol's avatar

Its really help me to improve my skills in coding.I would like to say thank you for sharing this wonderful information with us.I am making a website based on erp software uae .This all are really help me to include some additional features in my website.Thank you.

Please or to participate in this conversation.