Hi Railities
Here is a tip on how to work with CSRF token while ajax posting in rails 3.1.
Query:- While we are doing AJAX post , automatically the current session destroys in rails 3, and the current user automatically logged out.
Description for the query:-
While creating a rails app it creats a CSRF(Cross Site Request Forgey) token. When we do ajax POST basically the application must need that CSRF Token to be valid one . If it does not get any Token or does not match the perticular token value then as per authentication it destroys all session.
Also, this can be used to raise an ActionController::InvalidAuthenticityToken error .
Steps for prevention:-
There are two steps we generally can follow to avoid this .
Step1:-
Seting the X-CSRF-Token with ajax POST.
$.ajax({url:url,
type: 'POST', dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('
X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
data:{},
success: function(response){ }
});
Step 2:-
We can add a skip_filter in the perticular controller and action where the ajax request to be posted.
skip_filter :verify_authenticity_token, :action