Skip to content

Instantly share code, notes, and snippets.

@arnabc
Created April 13, 2011 06:49
Show Gist options
  • Save arnabc/917085 to your computer and use it in GitHub Desktop.
Save arnabc/917085 to your computer and use it in GitHub Desktop.
Rails authenticity token fix for non-idempotent XHR requests
// rails needs the authenticy_token param in non-idempotent request to protect from CSRF
var
// authenticity token name
AUTH_TOKEN_NAME = $( 'meta[name=csrf-param]' ).attr( 'content' ),
// authenticity token value
AUTH_TOKEN_VALUE = $( 'meta[name=csrf-token]' ).attr( 'content' );
// for each and every Ajax post request automatically append the 'authenticity_token' param
$( document ).ajaxSend( function ( event, xhr, settings ) {
// rails does not need the authenticity_token for GET requests
// if you do specify this param in GET requests, then IE
// will convert the request to POST, reason for this is Pure Love from Microsoft :-).
// well we send "null" to xhr.send(null) while making XHR GET requests, but if you specify some data
// other than 'null' in xhr.send() call in XHR GET, then IE converts the request to POST, all other
// browsers ignore that if Request type is GET but IE does not. Not sure what the spec
// says though.
if( settings.type.toUpperCase() === 'GET' ) return;
// if none of the token values defined then abort
if( !AUTH_TOKEN_NAME && !AUTH_TOKEN_VALUE ) return;
settings.data = settings.data || '';
settings.data += ( settings.data ? '&' : '' ) + AUTH_TOKEN_NAME + '=' + encodeURIComponent( AUTH_TOKEN_VALUE );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment