1

I'm trying to submit a Rails form using AJAX and data-remote.

The submission is triggered programmatically from javascript ($form.submit()). If I do it like this I receive an InvalidAuthenticityToken error.

I tried to submit the same form without javascript by simply clicking on the submit button and it worked. It seems that the authentication token is not sent when I submit the form using Javascript. I did some research and I tried the following options of adding the authentication token to the data being sent

  • adding the following line in the Controller skip_before_action :verify_authenticity_token, :only => :create
  • adding the following line inside the form_for block <%= f.hidden_field :authenticity_token, value: form_authenticity_token %>
  • adding :authenticity_token => true to the form_for params
  • setting config.action_view.embed_authenticity_token_in_remote_forms to true in development.rb

I tried using all the above and each of them helped me submit the form using javascript and get rid of the InvalidAuthenticityToken error, however, even though I still had the remote: true option, the request doesn't seem to be performed using AJAX since the page reloads and renders another view template.

This being said I would like to know how can I still submit the form from javascript but without getting any errors or having the page reload.

1 Answer 1

1

How about calling click() on the submit button instead of submit()? :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.