Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save balgarath/132763 to your computer and use it in GitHub Desktop.
Save balgarath/132763 to your computer and use it in GitHub Desktop.
##put this in your helper
# Passes the authenticity token for use in javascript
def yield_authenticity_token
if protect_against_forgery?
<<JAVASCRIPT
<script type='text/javascript'>
//<![CDATA[
window._auth_token_name = "#{request_forgery_protection_token}";
window._auth_token = "#{form_authenticity_token}";
//]]>
</script>
JAVASCRIPT
end
end
##put this at the top of your layout file
<%= yield_authenticity_token %>
##run this JS on page load
// All non-GET requests will add the authenticity token
// if not already present in the data packet
$("body").bind("ajaxSend", function(elm, xhr, s) {
if (s.type == "GET") return;
if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
if (s.data) {
s.data = s.data + "&";
} else {
s.data = "";
// if there was no data, jQuery didn't set the content-type
xhr.setRequestHeader("Content-Type", s.contentType);
}
s.data = s.data + encodeURIComponent(window._auth_token_name)
+ "=" + encodeURIComponent(window._auth_token);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment