Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Set the CSRF token for Rails when doing Ajax requests
define( ['jquery'], function ( $ ) {
var token = $( 'meta[name="csrf-token"]' ).attr( 'content' );
$.ajaxSetup( {
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-CSRF-Token', token );
}
});
return token;
});
@juliocesar

This comment has been minimized.

Copy link

@juliocesar juliocesar commented Apr 8, 2013

Since it's Rails, you may want a Sprockets-friendly version too.

// Ensure this is required somewhere by Sprockets after jQuery
//
//= require csrf-token
//
(function() {
  if ($) {
    var token = $( 'meta[name="csrf-token"]' ).attr( 'content' );

    $.ajaxSetup( {
      beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-CSRF-Token', token );
      }
    });      
  }
})();
@benschwarz

This comment has been minimized.

Copy link
Owner Author

@benschwarz benschwarz commented Apr 9, 2013

@juliocesar, Sprockets? Hell no.

@whatAboutJohn

This comment has been minimized.

Copy link

@whatAboutJohn whatAboutJohn commented Apr 18, 2016

This guy ^

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Apr 30, 2018

Can I ask you how to create this cookie in Rails? On ApplicationController maybe? On every NON-GET action?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment