Loading CSRF token on rails with AJAX


I've decided to implement my Rails site with only a single page load, and do everything else via AJAX. The problem is that the CSRF token which is generated in meta is invalidated once used to submit a signup or signin form. How can I update it without reloading the page?

I don't think that rails invalidates the CSRF meta token after every single request (or post or whatever) (if it didn't, frameworks like backbone.js would have a tough time :).

https://github.com/rails/rails/blob/7fb99e5743d88c04357e09960d112376428a6faa/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L100

You are probably making a request BEFORE the request you think is the invalid one without the correct token and thus rails deletes your session and subsequent requests are marked as invalid even if they pass the previously-correct token.


in each ajax request :

add to data :

authenticity_token: '<%= form_authenticity_token %>'


You can use beforeSend like below in your ajax call for put, post methods. $.ajax({ type: 'POST', beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, url: your url, data: data });