Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Last active August 29, 2015 14:23
Show Gist options
  • Save ifyouseewendy/62e27c7a42a3a3765019 to your computer and use it in GitHub Desktop.
Save ifyouseewendy/62e27c7a42a3a3765019 to your computer and use it in GitHub Desktop.
Make pure js POST request pass the `protect_from_forgery`, without Rails helper.

csrf.js

var csrftk = $("meta[name='csrf-token']").attr("content");

// Ajax set
$(document).ajaxSend(function(e, xhr, options) {
  xhr.setRequestHeader("X-CSRF-Token", csrftk);
});

// Form set
$('form').append('<input name="authenticity_token" type="hidden" value="'+csrftk+'"/>');

reports.html.erb

<html>
  <head>
    <%= csrf_meta_tag %>
    ...
  </head>
  <body>

    ...
    <%= javascript_include_tag 'csrf' %>
  </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment