-
-
Save mrhieu/4a7d6a003a08f26490ec to your computer and use it in GitHub Desktop.
CSRF token for AJAX POST in Rails 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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