Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails How to send an Authenticity Token in an Ajax Request without a form involved?

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.

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.

Is there a way to comply with CSRF protection generating a token so the controller is happy with it?

So far my Ajax function is:

  var functionOne = function() {
  var $form = $('#'  + tinyMCE.activeEditor.formElement.id);
  var action = $form.attr('action')
  $.ajax({
    method: "POST",
    url: action,
    data: $form.serialize(),
    dataType: 'script',
  });
};

This form is passing the following params

{"utf8"=>"✓", "_method"=>"patch", "open_ender"=>
  {"answer_id"=>"4",
  "content"=>"<p>testing text</p>"},
  "id"=>"5"}

I've tried including the following line inside the Ajax object

authenticity_token: $('meta[name=csrf-token]').attr('content'),

and this in the application layout head without success

$(function(){
  $.ajaxSetup({
  headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }
  });
});

UPDATE

Appart from Aniket's solution. Adding

authenticity_token: true 

in the form options hash solved the issue as well

like image 882
alopez02 Avatar asked Jan 20 '17 05:01

alopez02


1 Answers

Just pass a hidden field with value of authenticity token inside of your form and that should work.

<%= f.hidden_field :authenticity_token, value: form_authenticity_token %>

OR

<input type=hidden name="authenticity_token" value="<%= form_authenticity_token %>">
like image 111
Aniket Rao Avatar answered Oct 02 '22 15:10

Aniket Rao