Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionController::InvalidAuthenticityToken when disable JS/Ajax request

I have two forms with option remote: true; one sends an Ajax request to create action and the other one sends an Ajax request to destroy action.

All work fines when JavaScript is enabled, but if I disable JavaScript, then I click, I get this error:

ActionController::InvalidAuthenticityToken PersonsController#create 

Why this error is shown, and how can I fix it ?

note: I'm using Rails 4

Update

When I use a normal form without option remote: true, rails automatically inserts a hidden field for an authentication token, but when I use remote: true in my form there is no such field in the HTML code. It seems like when there is remote option, then Rails handles the authentication token differently, so how I can get this to work in both cases?

like image 308
medBouzid Avatar asked Oct 18 '13 15:10

medBouzid


1 Answers

Bizarrely, this behaviour was changed in rails 4. http://www.alfajango.com/blog/rails-4-whats-new/

Rails forms now will not render the CSRF field in the form unless you explicitly define it as an option to your form:

<%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %> <% end %> 

Adding this option allows you to gracefully degrade to a HTML fallback if Javascript is switched off.

like image 102
Dan Garland Avatar answered Oct 13 '22 19:10

Dan Garland