Created
August 21, 2009 19:59
-
-
Save collectiveidea/172391 to your computer and use it in GitHub Desktop.
How to get jQuery to work with Rail's Authenticity Token (protect_from_forgery)
This file contains hidden or 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 hidden or 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
I had an awful time getting this to work, but ATM I'm on the "bleeding edge" and seeing the blood, using Rails 6, webpacker, React. The problem I was having was a combination of load order and the actual instance of jQuery being used inside of @rails/ujs (and also tried jquery-ujs). None of them worked for me.
I was trying to make
$
available from inside myenvironment.js
file... By the time the$
was made available inside my react components, it was no longer the same instance as what was used in theujs
files, so the config didn't "take".My final "solution" that allowed my authenticity token to be sent properly from
$.ajax
in my react components was to import a "configured"$
manually like this:utils/jquery.js:
And inside React component:
I'm far from convinced that this is the best way to do this, but after several wasted hours, I'm just happy to have ANY way that works. I'm leaving this up in case it's either helpful for someone else, or someone knows a better way to get this working...