Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to a create session variable in JavaScript?

Tags:

javascript

Is it possible to create and update a session variable in JavaScript? Just like in PHP as I start sessions and initialize session variable.

I'm using some JavaScript function with PHP.

I'm just a beginner in JavaScript so please also refer me some good books.

like image 985
saint Avatar asked Apr 28 '11 12:04

saint


People also ask

Can you set a session variable in JavaScript?

You can't set session side session variables from Javascript . If you want to do this you need to create an AJAX POST to update this on the server though if the selection of a car is a major event it might just be easier to POST this. Save this answer.

How do you create a session variable?

Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user. The PHP code in the example below simply starts a new session.

How do you define a session variable?

What Are Session Variables? Session variables are special variables that exist only while the user's session with your application is active. Session variables are specific to each visitor to your site. They are used to store user-specific information that needs to be accessed by multiple pages in a web application.


2 Answers

The usual meaning of the term "Session variable" is: "Some data stored on the server, which is associated with a user's session via a token".

Assuming you are talking about client side JavaScript, then the short answer is "no" as it runs on the wrong computer.

You could use JS to make an HTTP request to the server, and have a server side programme store data in a session variable.

You could also use JS to store data in a cookie (and not set an expiry time so it expires at the end of the browser session)

like image 78
Quentin Avatar answered Sep 22 '22 23:09

Quentin


Well, taking a look at how sessions work, no, they cannot be created with javascript. You can, though, make an AJAX request to your PHP file to set one.

PHP:

<?php
session_start(); 
$_SESSION['mySession'] = 1;
?>

JS:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "session_maker.php", true);

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        alert("Done! Session created.");
    }
};
like image 28
mattsven Avatar answered Sep 22 '22 23:09

mattsven