tags:

views:

74

answers:

2
+1  Q: 

Ajax & session ids

How would you go about knowing that ajax requests are related?

Normally with HTTP-HTML requests, cookies would store a md5 hash representing a session id.

I would like to add, my ajax calls are cross-domain.

Updated:

Example:

var data1 = 'asdf';
$.ajax({
  url: 'http://differentdomain.com/ajax',
  data: 'data1=' + data1
});

Now with this ajax request being made by many clients (browsers/computers). I would like to know that they originated from a single browser session. I thought using a session id might be a solution.

Is there a standard pattern for AJAX & session ids? I am using Java on the server-side.

+1  A: 

AJAX requests are client-side. Client #1 using IE hits your site and processes any client-side code, all part of one session. Client #2 using Safari hits your site and processes any client-side code, all part of another session.

Unless you generate a session id, there isn't one available to you natively in javascript. If you can, for the sake of uniqueness, it's best to generate or get a session Id from server-side. If not, you can use a method like this.

If you're using PHP, you could do this:

var data1 = 'asdf';
var sessionId = '<?php echo session_id(); ?>';
$.ajax({ 
  url: 'http://differentdomain.com/ajax', 
  data: 'data1=' + data1 + '&sid=' + sessionId
}); 

If you're using ASP.NET, you could do this:

var data1 = 'asdf';
var sessionId = '<% =Session.SessionId %>';
$.ajax({ 
  url: 'http://differentdomain.com/ajax', 
  data: 'data1=' + data1 + '&sid=' + sessionId
}); 

If [some java web server] (like Tomcat), you could:

var data1 = 'asdf';
var sessionId = '<% session.getId() %>';
$.ajax({ 
  url: 'http://differentdomain.com/ajax', 
  data: 'data1=' + data1 + '&sid=' + sessionId
}); 
Byron Sommardahl
Any idea on doing this with java?
JavaRocky
Java would be the language you would use, but you'd have to be running through a web platform of some sort. Maybe you could use Tomcat (http://tomcat.apache.org/)?
Byron Sommardahl
A: 

I solved my problem by using UUID.randomUUID() and check if it has been used yet in my database. Then using the UUID as the session id.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

JavaRocky