title: Rails How to send an Authenticity Token in an Ajax Request without a form involved?
body: <p>For several reasons I need to send a post request to a controller via Ajax and I can't do it involving a form, it has to be a JS Ajax request written inside a file in assets > javascript or between  tags. </p>
  
  <p>I've written a function which seems to pass data correctly. However, it isn't passing a valid Authenticity Token, hence not allowing the request to go through.</p>
  
  <p>Is there a way to comply with CSRF protection generating a token so the controller is happy with it?</p>
  
  <p><strong>So far my Ajax function is:</strong></p>
  
  <pre><code>  var functionOne = function() {
    var $form = $('#'  + tinyMCE.activeEditor.formElement.id);
    var action = $form.attr('action')
    $.ajax({
      method: "POST",
      url: action,
      data: $form.serialize(),
      dataType: 'script',
    });
  };
  </code></pre>
  
  <p><strong>This form is passing the following params</strong></p>
  
  <pre><code>{"utf8"=&gt;"✓", "_method"=&gt;"patch", "open_ender"=&gt;
    {"answer_id"=&gt;"4",
    "content"=&gt;"&lt;p&gt;testing text&lt;/p&gt;"},
    "id"=&gt;"5"}
  </code></pre>
  
  <p><strong>I've tried including the following line inside the Ajax object</strong></p>
  
  <pre><code>authenticity_token: $('meta[name=csrf-token]').attr('content'),
  </code></pre>
  
  <p><strong>and this in the application layout head without success</strong></p>
  
  <pre><code>$(function(){
    $.ajaxSetup({
    headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }
    });
  });
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Appart from Aniket's solution. Adding </p>
  
  <pre><code>authenticity_token: true 
  </code></pre>
  
  <p>in the form options hash solved the issue as well</p>