How to get CSRF token Value at javaScript

44.2k Views Asked by At

I have requirement like that, when I send request, CSRF-token should be send with it. I Explore some SO questions, But I can't find Solution.

I have written Code like bellow to add token when request being sent,

 var send = XMLHttpRequest.prototype.send,
        token = $('meta[name=csrf-token]').attr('content');
    XMLHttpRequest.prototype.send = function(data) {
        this.setRequestHeader('X-CSRF-Token', "xyz12345");
        //this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
        return send.apply(this, arguments);
    }

This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.

I have tried ajax function as below . `

$.ajax({
            type: "POST",
            url: "/test/"
            //data: { CSRF: getCSRFTokenValue()}
        }).done(function (data) {
        var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
        if (csrfToken) {
            var cookie = JSON.parse($.cookie('helloween'));
            cookie.csrf = csrfToken;
            $.cookie('helloween', JSON.stringify(cookie));
        }

        $('#helloweenMessage').html(data.message);

    });

But it is not Yet Worked. So my question is: How to get js side CSRF-Token Value?

2

There are 2 best solutions below

0
Niraj On BEST ANSWER

I get my CSRF Token by this way, By adding function :

$.get('CSRFTokenManager.do', function(data) {
   var send = XMLHttpRequest.prototype.send,
   token =data;
   document.cookie='X-CSRF-Token='+token;
   XMLHttpRequest.prototype.send = function(data) {
       this.setRequestHeader('X-CSRF-Token',token);
       //dojo.cookie("X-CSRF-Token", "");

       return send.apply(this, arguments);
   };
});

Where CSRFTokenManager.do will be called from CSRFTokenManager Class.
Now It is adding token in header and cookie in every request.

0
rameezmeans On

you need to do this in new Laravel

var csrf = document.querySelector('meta[name="csrf-token"]').content;
    $.ajax({
        url: 'url',
        type: "POST",
        data: { 'value': value, '_token': csrf },
        success: function (response) {
            console.log('value set');
        }
    });