Skip to content

Instantly share code, notes, and snippets.

@yurifrl
Forked from collectiveidea/application.html.erb
Created March 12, 2014 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurifrl/9506444 to your computer and use it in GitHub Desktop.
Save yurifrl/9506444 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>My Rails App</title>
<%- if protect_against_forgery? -%>
<meta name="authenticity-token" id="authenticity-token" content="<%= form_authenticity_token %>" />
<%- end -%>
<%= javascript_include_tag 'jquery', 'rails' %>
</head>
<body>
<h1>Using jQuery with Rails' Authenticity Token</h1>
<p>
By putting the authenticity token in the head, we can easily grab it from JS.
</p>
</body>
</html>
(function($) {
$.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;
$.authenticityToken = function() {
return $('#authenticity-token').attr('content');
};
$(document).ajaxSend(function(event, request, settings) {
if (settings.type == 'post') {
settings.data = (settings.data ? settings.data + "&" : "")
+ "authenticity_token=" + encodeURIComponent($.authenticityToken());
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment