Rails not reloading session on ajax post Rails not reloading session on ajax post ajax ajax

Rails not reloading session on ajax post


I'm going to answer my own question as I've managed to work out what was going on. I'll post it here in case it's useful to anyone else!

After investigating further, I worked out that the code that was supposed to be setting the request header with the CSRF token, wasn't. This was the original code:

$(document).ajaxSend(function(e, xhr, options) {  var token = $("meta[name='csrf-token']").attr('content');  xhr.setRequestHeader('X-CSRF-Token', token);});

What was happening was that this code wasn't setting the header, Rails was receiving an Ajax request, the token didn't match and it was resetting the session. This used to raise an ActionController::InvalidAuthenticityToken error (I suppose I would have caught this earlier if an error was raised... oh well), but since Rails 3.0.4 it now just quietly resets the session.

So to send the token in the header, you have to do this (many thanks to this marvellous blog post):

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

And now it all works as it should. Which is nice.


I found another case:

have you set the 'csrf_meta_tag' in your application layout file?

in my case, I didn't set that tag, and met the same problem with yours.

And after setting the csrf_meta_tag in app/views/layouts/application.html.erb, everything works fine!

At last, thank you for helping me found the root cause ! thanks a lot ~


That's what the official jquery-ujs rails adapter is for in the 3.0 series. You have to remember to keep it updated when upgrading rails versions though.

For me, upgrading from 3.0.3 to 3.0.8.rc4 meant also manually fetching the src/rails.js file from the linked repo.

Since Rails 3.1 finally made the switch to jQuery, things should auto-update in the future via the jquery-rails gem when updating rails (and using 3.1's built-in asset pipeline)