Set the CSRF token for Rails when doing AJAX requests


By default, Rails requires CSRF token on POST, PUT and DELETE requests.

If you are not using Rails built-in AJAX remote: true you probably need to add CSRF token to your AJAX request header manually.

Since in Rails 5, Rails team get rid of jquery-ujs and develop rails-ujs instead, the syntax for Rails 4 and Rails 5 are a litle bit different, but the idea of the solution stays the same.

These solutions below assume that we use jQuery for AJAX requests.

Rails 4

For a single AJAX request:

$.ajax({
  ...
  beforeSend: $.rails.CSRFProtection
});

Or make it available to all requests:

$(document).ready(function() {
  $.ajaxSetup( {
    beforeSend: $.rails.CSRFProtection
  });
});

Rails 5

For a single AJAX request:

$.ajax({
  ...
  beforeSend: Rails.CSRFProtection
});

Or make it available to all requests:

$(document).ready(function() {
  $.ajaxSetup( {
    beforeSend: Rails.CSRFProtection
  });
});

References