7

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?

3
  • What is the question? Is the question how you get the CSRF header or a value into a cookie? Commented Sep 10, 2015 at 5:09
  • @limelights, I have CSRF-token in responce now, same token I want to pass in request also, So, just wanted to get Value of CSEF-Token .Here ajax function is not by me. it's taken. Commented Sep 10, 2015 at 5:14
  • By adding this: token = $('meta[name=csrf-token]').attr('content'); I'm getting token as undefined. Commented Sep 10, 2015 at 5:47

2 Answers 2

3

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');
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.