Created
March 31, 2011 17:31
-
-
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
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
In all layout files (ex. views/layouts/application.html.erb) | |
<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? -%> |
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
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