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
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 %>">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With