2

I am trying to create a session from JQuery to my Sinatra backend. When I send a POST request outside of Ajax, using something like POSTman, I am able to set a session, but when I send via JQuery, I just get NULL in return. How do I create a session using AJAX?Should I be actually doing this via AJAX or should I jus have a login screen?

This is my session (and some other pertinent) setting code:

set :protection, :except => [:http_origin, :remote_token] //I put this because Sinatra was denying the request before
set :session_secret, "My session secret"

post '/session' do
    session[:user_id] ||= 'hihiiddasdah'
    session[:user_id].to_json
end

delete '/session' do
    session.clear
    session[:user_id].to_json

end

get '/session' do
    session[:user_id].to_json
end

and this is my JQuery code for getting the session:

$.post(URL + 'session', {function(data) {console.log(data);});
Daryll Santos
  • 2,031
  • 3
  • 22
  • 40
  • is the ajax request being made from the same domain as the server URL? – Jonah Sep 20 '13 at 09:47
  • Well they are both in the localhost but they are not in the same folders. I put response['Access-Control-Allow-Origin'] = '*' in Sinatra. (I plan on just making it work first then slowly add security back in.) – Daryll Santos Sep 20 '13 at 09:49
  • Can you open up the chrome console F12 and lmk what, if any, errors you are seeing in the output – Jonah Sep 20 '13 at 09:59
  • Okay. Here's what happens, I am able to log 'hihiiddasdah' after I "set" the session. But succeeding requests to `GET '/session'` result in `NULL`. When I check Session Storage and Cookie Storage in the Resources tab in chrome, there aren't any sessions and cookies set. – Daryll Santos Sep 20 '13 at 10:06
  • And you are running the get request from the same url as you do the initial post, correct? also just to rule out the obvious: you are using cookie based sessions? EDIT: one other thing you should set `content_type :json` when returning json. i don't *think* that would cause this problem but you should do it anyway – Jonah Sep 20 '13 at 10:30
  • Yes, I have set `content_type :json` in the `before do` clause in Sinatra, and I am running the get request from the same URL. When you say cookie-based sessions, what exactly do you mean? I have `enable :sessions` up top of the Sinatra app if that's what you mean. BTW, I really appreciate your help, I'm at wit's end here. – Daryll Santos Sep 20 '13 at 10:41
  • Okay, cookie-based sessions are the default, so you should be good there. If you want to throw your whole sample app up on pastebin, I can try running it locally and see if I can figure it out. – Jonah Sep 20 '13 at 10:51
  • Good idea, I'll try to get it to the simplest form possible first, maybe I can solve it by myself. If I still can't solve it, I'll send the pastebin later. Once again, I appreciate the help – Daryll Santos Sep 20 '13 at 11:19

0 Answers0