Answers.Body: <p>This is the syntax for Craft 3:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName }}";
      window.csrfTokenValue = "{{ craft.app.request.csrfToken }}";
  &lt;/script&gt;
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-06-28T19:12:46.283Z
Answers.LastActivityDate: 2018-06-28T19:12:46.283Z
Answers.UserDisplayName: Ryan
Answers.Body: <p>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!</p>
  <p>The key is to <strong>make your CSRF token name &amp; value available in your front-end JS</strong>. You can then pass that into your AJAX call as an additional value.</p>
  <p>There are a few ways to push the CSRF data to the front-end, so this is simply one example:</p>
  <pre><code>{# Get CSRF token info in Twig #}
  {% set csrfToken = {
      name: craft.app.config.general.csrfTokenName,
      value: craft.app.request.csrfToken,
  } %}
  
  {# Pass CSRF token through to JavaScript (via the page head) #}
  {% js &quot;window.csrfToken = #{csrfToken|json_encode|raw};&quot; at head %}
  </code></pre>
  <p>Once you have the CSRF info on the front-end, simply add it to your AJAX data...</p>
  <pre class="lang-js prettyprint-override"><code>$(function(){
      // Whatever data is being passed via AJAX
      const data = { id: 100 };
  
      // Append CSRF Token
      data[window.csrfToken.name] = window.csrfToken.value;
  
      // Make the AJAX call
      $.post('actions/example-controller/example-action', data, function(response) {
          console.log('success', response, data);
      });
  });
  </code></pre>
  <p>That's it! Your AJAX call should now submit properly.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-11-03T07:20:56.763Z
Answers.Text: If anyone wonders (like I did) how to do that when uploading files – here is the answer: http://stackoverflow.com/a/16762012/2342963
Answers.UserDisplayName: medoingthings
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-02-27T00:27:45.417Z
Answers.Text: There is a section in the documentation on [Ajax](https://craftcms.com/docs/4.x/dev/controller-actions.html#ajax) that provides some additional methods for working with CSRF protection!
Answers.UserDisplayName: August Miller
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2015-01-14T18:41:40.313Z
Answers.LastActivityDate: 2024-02-26T23:59:38.017Z
Answers.LastEditDate: 2024-02-26T23:59:38.017Z
Answers.UserDisplayName: Lindsey D
Body: <p>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.</p>
  
  <pre class="lang-html prettyprint-override"><code>&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;
  </code></pre>
  
  <p>Here is my AJAX that I am testing with.</p>
  
  <pre class="lang-js prettyprint-override"><code>$(function(){
      var data = { id: 100 };
      $.post("/actions/gistClient/exampleAjax", data, function(response) {
          console.log("success", response, data);
      });
  });
  </code></pre>
  
  <p>Here is my controller action</p>
  
  <pre class="lang-php prettyprint-override"><code>public function actionExampleAjax()
  {
      $this-&gt;requireAjaxRequest();
      // ... whatever your AJAX does...
      $response = array('response' =&gt; 'Round trip via AJAX!');
      $this-&gt;returnJson($response);
  }
  </code></pre>
  
  <p>Is it possible to disable CSRF for certain routes? Alternatively, how would I pass CSRF through AJAX to the controller action?</p>
  
Tags: <ajax><csrf>
Title: How can I use CSRF protection with AJAX routes?
ThreadText: # How can I use CSRF protection with AJAX routes?
  
  (Asked by: username_0 on 2015-01-14)
  
  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.
  
  ```html
  <div id="message" class="pane">
      <h2>Bad Request</h2>
      <p>The CSRF token could not be verified.</p>
  </div>
  
  ```
  
  Here is my AJAX that I am testing with.
  
  ```js
  $(function(){
      var data = { id: 100 };
      $.post("/actions/gistClient/exampleAjax", data, function(response) {
          console.log("success", response, data);
      });
  });
  
  ```
  
  Here is my controller action
  
  ```php
  public function actionExampleAjax()
  {
      $this->requireAjaxRequest();
      // ... whatever your AJAX does...
      $response = array('response' => 'Round trip via AJAX!');
      $this->returnJson($response);
  }
  
  ```
  
  Is it possible to disable CSRF for certain routes? Alternatively, how would I pass CSRF through AJAX to the controller action?
  
  **Tags:** ajax, csrf
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_2 on 2015-01-14. Score: 22 | Accepted answer
  
  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 & 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:
  
  ```
  {# Get CSRF token info in Twig #}
  {% set csrfToken = {
      name: craft.app.config.general.csrfTokenName,
      value: craft.app.request.csrfToken,
  } %}
  
  {# Pass CSRF token through to JavaScript (via the page head) #}
  {% js "window.csrfToken = #{csrfToken|json_encode|raw};" at head %}
  
  ```
  
  Once you have the CSRF info on the front-end, simply add it to your AJAX data...
  
  ```js
  $(function(){
      // Whatever data is being passed via AJAX
      const data = { id: 100 };
  
      // Append CSRF Token
      data[window.csrfToken.name] = window.csrfToken.value;
  
      // Make the AJAX call
      $.post('actions/example-controller/example-action', data, function(response) {
          console.log('success', response, data);
      });
  });
  
  ```
  
  That's it! Your AJAX call should now submit properly.
  
  > **Comments:**
  > **username_3**: If anyone wonders (like I did) how to do that when uploading files – here is the answer: http://stackoverflow.com/a/16762012/2342963  
  > **username_4**: There is a section in the documentation on [Ajax](https://craftcms.com/docs/4.x/dev/controller-actions.html#ajax) that provides some additional methods for working with CSRF protection!  
  
  ---
  
  ### Answer by username_1 on 2018-06-28. Score: 10
  
  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>
  
  ```
  
  
  ---
  
  