Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Render JSON - Session Lost?

i am trying to make some Ajax calls to an controller which responds with JSON.

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

The first time this action gets called by an authed user everything is ok and session[:user] is != nil. The second time it gets called it is nil!

So it seems like rails is loosing it's session as soon as i do render :json. I figured out that within the first call rails overrides the *_session-cookie with a new one. As consequence of that rails doesn't know about the initial, authed, session.

If i don't render the response as JSON everything works fine.

How to force rails to set the same sessionid in JSON rendered pages as in normal views?

like image 565
gorootde Avatar asked Dec 14 '11 21:12

gorootde


2 Answers

After six days of searching I finally made it:

Seems like rails destroys the session because of the missing X-CSRF-Token Header. I am adding this header now in in the ajaxSend Hook of JQuery:

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

It's working as expected now.

like image 144
gorootde Avatar answered Nov 15 '22 04:11

gorootde


I put that in beforeSend method:

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()}
        });
    }

works great if you don't need to use other way of ajax request(in this way you should add beforeSend to all ajax requests)

like image 28
Vladyslav Avatar answered Nov 15 '22 06:11

Vladyslav