Rails - How to add CSRF Protection to forms created in javascript?

后端 未结 5 1000
悲&欢浪女
悲&欢浪女 2020-12-04 14:37

I\'m using backbone.js and it works great. but the forms I\'m creating as a javascript template lacks the rails csrf protection token. How do I add it to templates I\'m crea

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 14:52

    As for Rails 4.2.2 you are not allowed to use

    <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
    

    from your .js.erb assets file.

    However You can create the form inside the .js.erb file and in the view containing the form .html.erb file use the hidden_field_tag helper to generate the token element. As this element is going to be generated outside the form you can use jquery to append this element to the form.

    Case of study: SweetAlert (first version, version too seems to have solved this problem)

    show.js.erb

    $('.js-button-apply-offer').click(function(e) {
    var urlOffer = $(this).attr('data-url-offer');
    var modalParams = {
        type: 'warning',
        title: 'add file',
        text: '

    Need to add a file before continuing

    ' // This is a hack for Sweet alert, solved in SweetAlert2 Consider upgrade +"
    " + "\n" +"
    ", html: true, showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Send', cancelButtonText: 'Cancel', closeOnConfirm: false } swal(modalParams, function(){ var form_token = $('#form_token'); $('#formCustomCV').append(form_token).submit(); //update to submit using ajax });

    show.html.erb

    <%= button_tag t('offers.offer.apply'),
      class: 'center-block btn btn-success js-button-apply-offer',
      id: "js-button-apply-offer",
      data: {
        url_offer: apply_talents_offer_path(@offer),
      } 
    %>
    <%= hidden_field_tag :authenticity_token, form_authenticity_token, id: :form_token %>
    

提交回复
热议问题