Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CSRF token Value at javaScript

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?

like image 284
Niraj Avatar asked Sep 10 '15 04:09

Niraj


1 Answers

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');
        }
    });
like image 200
rameezmeans Avatar answered Nov 27 '22 21:11

rameezmeans