3

I have built a plugin that simply makes requests to a 3rd party API. I am calling my plugin action via ajax.

I don't have a form on this page currently. Here is what I am using, but I am getting the error The CSRF token could not be verified.

I thought I could just put a hidden input field somewhere on my template:

twig

<input type="hidden" name="{{ craft.config.csrfTokenName }}" value="{{ craft.request.csrfToken }}">

Here is what my ajax call looks like...

jquery

var data = {
    'thing': value,
    'thing': value
};

data[window.csrfTokenName] = window.csrfTokenValue;

$.ajax({
    'type': 'post',
    'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cache': false,
    'data': data,
    'url': 'myplugin/doAction',
    'dataType': 'json',
    'timeout': 50000
}).done(function (response) {
    callback(response);
}).fail(function (error) {
    // Total fail.
});

Later on in my site I will have a form that accepts user input, so I would like to keep CSRF enabled for the entire site. Perhaps I need to "skip" the CSRF token for these requests?

5

You need to pass the token and name into javascript. Easiest is to just have a script tag somewhere.

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.config.csrfTokenName }}";
    window.csrfTokenValue = "{{ craft.request.csrfTokenValue }}";
</script>

Now they will be available to your ajax call.

  • Thank you! I read that on the docs, but thought... well I can see that I am setting it so whats the big deal? I'd also like to point out to (anyone else) make sure that the above script needs to be placed above/before your ajax script is called. – Damon Nov 20 '15 at 19:02
  • If your ajax call is triggered by a user event (such as click), it can go anywhere, just append the csrf stuff to your data inside the event handler. – megatrond Nov 20 '15 at 19:04
  • Ah - you are right. It looks like I must of run into a cache issue. I was getting that the csrf config did not exist otherwise. All cool now - thank you again! – Damon Nov 20 '15 at 19:25
4

This is the syntax for Craft 3:

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken }}";
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.