Rails Render JSON - session loss?

I am trying to make some Ajax calls to a controller that responds with JSON.

if session[:user]
  render :json => "Some Data"
else
  render :json => "You are not logged in"
end

The first time this action is called by an offline user, everything is fine, and session[:user]- != nil. The second time he's called it nil!

So it seems that the rails are losing session as soon as I do render :json. I found out that within the first call, the rails redefine *_sessioncookies with a new one. As a consequence of the fact that the rails do not know about the original, autonomous session.

If I do not give the answer as JSON, everything works fine.

How to make rails set the same session file in displayed JSON pages, as in regular views?

+5
2

, , :

, - X-CSRF-Token. ajaxSend Hook JQuery:

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

.

+8

beforeSend:

function goAjax(urlAddress,dataObject,successFunction,errorFunction){
        $.ajax({
              type: "POST",
              url: urlAddress,
              beforeSend: function ( xhr ) {
                    xhr.setRequestHeader("X-CSRF-Token", $('meta[name=csrf-token]').attr('content'));
              },
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              processData: false,
              data: JSON.stringify(dataObject),
              context: document.body,
              success: function(data,status){ successFunction(data,status);},
              error: function(data,status){ errorFunction()}
        });
    }

, ajax- ( beforeSend ajax)

+1

All Articles