Skip to content

Instantly share code, notes, and snippets.

@benschwarz
Created April 7, 2013 23:11
Show Gist options
  • Save benschwarz/5333009 to your computer and use it in GitHub Desktop.
Save benschwarz/5333009 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

@juliocesar, Sprockets? Hell no.

@whatAboutJohn
Copy link

This guy ^

Copy link

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