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?
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:
Adding this option allows you to gracefully degrade to a HTML fallback if Javascript is switched off.
If there is no csrf field(a hidden field) inside the form, the submission can't be authenticated by Rails server.
If you make the form by
form_tag
, this situation will happen. The better approach is to useform_for
for a resource(new object or an existing object in db) and csrf field will be built by Rails automatically.In my case i just had to add this line in my page:
Me too faced the same problem. I have used form_tag to create custom remote form, but i got the the following error,
I found that this is because in rail 4 wont add authenticity toke by default, so i added the following line in application.rb file,
which automatically verify the toke when submitting the remote forms. This solves the problem for me. Hope this will help some one.