Skip to content

Instantly share code, notes, and snippets.

@monicao
Created March 31, 2011 17:31
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 monicao/896828 to your computer and use it in GitHub Desktop.
Save monicao/896828 to your computer and use it in GitHub Desktop.
helps with passing the request forgery protection token back to rails when using ajax with jQuery
In all layout files (ex. views/layouts/application.html.erb)
<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? -%>
jQuery(document).ready(function(){
// Add the authenticity_token with the parameters submitted via ajax
$(document).ajaxSend(function(event, request, settings) {
if ( settings.type == 'post' ) {
settings.data = (settings.data ? settings.data + "&" : "")
+ "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment