简体   繁体   中英

Rails 4 exception from CoffeeScript: ActionController::InvalidAuthenticityToken

I have ActionController::InvalidAuthenticityToken when trying to submit dynamically created form from coffeescript.

I tried to pass authenticity_token in my form request, but had no success. Can you please help me?

My CoffeeDcript code;

    upload_form = $('<form>', {
      'action': '/save_orders',
      'method': 'post'
    }).append($('<input>', {
      'data': my_json
    }));
    upload_form.submit();

Please note, that i neeed to create and submit form dynamically, so i can't prepare it on html page and then reuse in js. Also it should be form request (not ajax)

Somewhere in a rails view (eg application.html.erb file) you can set a global js variable like this:

window._token = '<%= form_authenticity_token %>';

Then when create a form you can append it to the form like this:

upload_form = $('<form>', {
  'action': '/save_orders',
  'method': 'post'
}).append($('<input>', {
  'data': my_json
})).append($('<input>', {
  'type': 'hidden',
  'name': 'authenticity_token',
  'value': window._token
}));
upload_form.submit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM