How can I use CSRF protection with AJAX routes? I have CSRF enabled on my install. I have a bunch of frontend forms so CSRF is pretty important for me. However, when I use AJAX to post to a controller action I get the following error.

&lt;div id="message" class="pane"&gt;
    &lt;h2&gt;Bad Request&lt;/h2&gt;
    &lt;p&gt;The CSRF token could not be verified.&lt;/p&gt;
&lt;/div&gt;


Here is my AJAX that I am testing with.

$(function(){
    var data = { id: 100 };
    $.post("/actions/gistClient/exampleAjax", data, function(response) {
        console.log("success", response, data);
    });
});


Here is my controller action

public function actionExampleAjax()
{
    $this-&gt;requireAjaxRequest();
    // ... whatever your AJAX does...
    $response = array('response' =&gt; 'Round trip via AJAX!');
    $this-&gt;returnJson($response);
}


Is it possible to disable CSRF for certain routes? Alternatively, how would I pass CSRF through AJAX to the controller action?
Disabling the CSRF protection is probably a bad idea... it's in there for a reason. But you can easily add your CSRF data to an AJAX call, and it works very well!

The key is to make your CSRF token name &amp; value available in your front-end JS. You can then pass that into your AJAX call as an additional value.

There are a few ways to push the CSRF data to the front-end, so this is simply one example:

{% set csrfToken = {
    csrfTokenName: craft.app.config.general.csrfTokenName,
    csrfTokenValue: craft.app.request.csrfToken,
} %}

&lt;script type="text/javascript"&gt;
    window.Craft = {{ csrfToken|json_encode|raw }};
&lt;/script&gt;


Once you've got those values on the front-end, adding them to your AJAX call is relatively easy:

$(function(){
    var data = { id: 100 };
    data[window.Craft.csrfTokenName] = window.Craft.csrfTokenValue; // Append CSRF Token
    $.post("/actions/gistClient/exampleAjax", data, function(response) {
        console.log("success", response, data);
    });
});


That's it! Your AJAX call should now submit properly.