Search code examples
jqueryruby-on-rails-4csrf-protection

In a rails 4 app I am having trouble passing the csrf token with an answer in jquery


Page html:

<head>
  ...
  <%= csrf_meta_tags %>
  ...
</head>

jquery:

$(".on_click").click(function() {
    $("#spinner").show();

    var token = $('meta[name="csrf-token"]').attr('content');
    var ans = $(this).attr('ans');
    var url = ... + "/?ans=" + ans + "&_csrf=" + token;

    $.post(url, function(html) {
        $("#spinner").hide();
    });
});

UPDATE:

oops... forgot to mention the error: Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)

Thanks in advance.


Solution

  • You can set the token to send in all request in such way:

    $.ajaxSetup({
      headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      }
    });
    

    Or for a specific request such as yours:

    $.ajax({ 
        url: 'YOUR URL HERE',
        type: 'POST',
        beforeSend: function(xhr) {
          xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
          data: //data here,
          success: function(response) {
            //some code
          }
        }
    });