views:

121

answers:

2

is it possible to create session variables with jquery or javascript or do i have to use ajax to call a php that does that?

+6  A: 

You'll need to use a server-request. Javascript operates only on the client, and session data is stored on the server.

// example of passing variable 'name' to server-script for session-data-storage
$.post("createSession.php", {"name":"jonathan"}, function(results) {
  alert(results); // alerts 'Updated'
});

And on the server, something like:

session_start();
$_SESSION["name"] = $_POST["name"];
print "Updated"; // What will be passed to Javascript "alert" command.
Jonathan Sampson
js can create cookies but not sessions?
weng
Cookies exist on the user computer, but sessions exist on the server hosting the website.
Jonathan Sampson
That is why cookies are less-secure than session variables. Users have complete access to cookies (since they exist on the users computer). But session data is stored on the server, where access is restricted generally.
Jonathan Sampson
+1 nice to see an answer 4 times longer than the question :)
Jay
A: 

You can just use php to create a session variable, no javascript required.

<?php
session_start();  
$_SESSION['uniquely'] = microtime(true);
?>

I suppose if you wanted to create a session when a user hovered over an image, or clicked on a link, you could use jquery to make an ajax call to set the session.

Thoughts?

superUntitled