Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devise Logging User out on AJAX request. Rails 3.1

I have a controller which uses AJAX for CRUD, however whenever I click on one of my remote links (Delete for example) I see the rails server has decided to log me out and redirect me. Inspection of the server logs state that it cannot verify CSRF Authenticity. How do I include the CSRF token in my request?

Running: - Rails 3.1 - Devise 1.4.4 - jquery-rails 1.0.13

Relevant Controller Action:

 def destroy
     @article = Article.find(params[:id])
      if @article.destroy
        flash[:notice] = "Article deleted."
        respond_to do |format|
        format.html{redirect_to articles_path}
        format.js{}
      end
      else
        flash[:error] = "Try Again."
        redirect_to :back
      end

Layouts/application.html.erb

      <head>
    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-1.1.1.min.css>
    <%= stylesheet_link_tag "application" %>
    <%= javascript_include_tag :defaults %>
   <script type="text/javascript">jQuery.ajaxSetup({ beforeSend: function (xhr) { xhr.setRequestHeader("Accept", "text/javascript"); } });</script>
    <%= csrf_meta_tag %>
    <%= yield(:head) %>
  </head>

Thanks in advance.

like image 380
Xavier Denis Avatar asked Sep 01 '11 04:09

Xavier Denis


2 Answers

Rails 3.1 uses the gem 'jquery-rails', which wants you to have this in your application.js file:

//= require jquery
//= require jquery_ujs

I had forgotten the jquery_ujs and was getting the same problem as you.

like image 172
Plattsy Avatar answered Sep 25 '22 23:09

Plattsy


You should have this in your html page:

<%= csrf_meta_tag %>

which generates the following:

<meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="the token comes here"/>

Whenever you do POST (DELETE, PUT are actually POST but with _method set dependently), you should get include the {authenticity_token: "the token comes here"} in the data your post together with.

like image 44
PeterWong Avatar answered Sep 23 '22 23:09

PeterWong