What is the best way to append CSRF token without using a form? 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

&lt;input type="hidden" name="{{ craft.config.csrfTokenName }}" value="{{ craft.request.csrfToken }}"&gt;


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?
You need to pass the token and name into javascript. Easiest is to just have a script tag somewhere.

&lt;script type="text/javascript"&gt;
    window.csrfTokenName = "{{ craft.config.csrfTokenName }}";
    window.csrfTokenValue = "{{ craft.request.csrfTokenValue }}";
&lt;/script&gt;


Now they will be available to your ajax call.