- Set Session Variable Using JavaScript in PHP
- How to access Session variables and set them in javascript?
- Clearing a Session variable using javascript
- How can I set a session var using javascript and get it via php code
- How do I make a PHP session variable equals to JS variable?
- How to insert javascript value into the php session variable
- How do I access session variable from php in external javascript
- Session variable with javascript
- # Table of Contents
- # How to access and set Session Variables in JavaScript
- # sessionStorage vs localStorage in JavaScript
- # Using the localStorage property to access and set variables
- # Additional Resources
Set Session Variable Using JavaScript in PHP
In above code snippet I have initialized global variable myvar with value stored into php session variable into script file before general.js file is referenced in script.It will be accessible in general.js file
How to access Session variables and set them in javascript?
Accessing & Assigning the Session Variable using Javascript:
Assigning the ASP.NET Session Variable using Javascript:
function SetUserName()
var userName = "Shekhar Shete";
'';
alert('');
>
Accessing ASP.NET Session variable using Javascript:
function GetUserName()
var username = '';
alert(username );
>
Clearing a Session variable using javascript
Here is what I have figured out to work
$(function () $('.close').click('.close', function() $.get('php/scripts/clear/employeeError.php', function(data) alert("Server Returned: " + data); //Used to verify script runs
>);
return false;
>);
>);
Basically what happens now is I use this inline script to listen for the .close and then it will call the script to unset the session variable.
How can I set a session var using javascript and get it via php code
You can’t set a server session variable directly from JS.
To do that you can make an AJAX call to a PHP script passing the value you want to set, and set it server side:
$('#editRole').on('show.bs.modal', function (e) <
$roleID = $(e.relatedTarget).attr('data-id');
//ajax call
$.ajax( url: "set_session.php",
data: < role: $roleID >
>);
>);
set_session.php
//preliminary code
Session::put('roleID', $request->input('role') );
How do I make a PHP session variable equals to JS variable?
You can use Ajax for that:
var httpRequest = null;
function getHttpObject()
if (httpRequest != null)
return;
if (window.XMLHttpRequest) < // Mozilla, Safari, .
httpRequest = new XMLHttpRequest();
> else if (window.ActiveXObject) < // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
>
>
function getLocation()
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(showPosition);
>
else
>
function showPosition(position)
<
document.getElementById('inputfield3').value = position.coords.latitude;
document.getElementById('inputfield4').value = position.coords.longitude;
getHttpObject();
// I don't know how to get the positions for showPosition, so you may have to change this part.
httpRequest.open("GET", "set_position.php?lat=" + position.coords.latitude + "&lon post" action="set_positions.php" >
function getLocation()
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(showPosition);
>
else
>
function showPosition(position)
<
document.getElementById('inputfield3').value = position.coords.latitude;
document.getElementById('inputfield4').value = position.coords.longitude;
document.getElementById('form1').submit();
>
So you’ll receive those fields in your PHP script. Note that those fields can be hidden fields too if you doesn’t want to user to change its value.
How to insert javascript value into the php session variable
You cannot access it directly (the way you are doing). However, it can be done using AJAX.
Here is the perfectly working solution.
$(document).ready(function()
function languageChange()
var lang = $('#websites1 option:selected').val();
return lang;
>
$('#websites1').change(function(e) <
var lang = languageChange();
var dataString = 'lang=' + lang;
$.ajax(
type: "POST",
url: "pass_value.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(response)
alert(response.message);
>
>);
return false;
>);
>);
//pass_value.php
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
$_SESSION['SESS_LANGUAGE'] = 'This is my PHP session var --->'.$_SESSION['SESS_LANGUAGE'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
Once you run the code, simply select any of the other options from the dropdown menu and you will receive an alert that gives you the value of the php session variable along with the custom text that I added to it.
If you want to run my solution on your end, make sure you point to core jQuery js file correctly. My jquery code points to src="https://www.itcodar.com/php/js/jquery_1.7.1_min.js" . Make sure you update this.
How do I access session variable from php in external javascript
If you want to call php variable in external js file then you have to store value in input.
//the script from which I want to get $SESSION_['user_id']
$(function() var user_id = $('.user_id').val();
alert(user_id);
>);
And if you want to use in same file then you can directly use php echo.
//content..
var user_id = "";
// console.log(user_id); that file you'll get that id.
Session variable with javascript
Last updated: Apr 21, 2023
Reading time · 4 min
# Table of Contents
# How to access and set Session Variables in JavaScript
You can use sessionStorage.setItem() and the sessionStorage.getItem() method to access and set session variables in JavaScript.
The sessionStorage API enables you to store and access data saved in the current page session.
Here is the HTML for the example. It simply loads a JS script.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="id">bobbyhadz.comdiv> script type="module" src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!/** * Setting session variables */ sessionStorage.setItem('first', 'bobby'); sessionStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; sessionStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing session variables */ console.log(sessionStorage.getItem('first')); // 👉️ bobby console.log(sessionStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(sessionStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
The sessionStorage property is used to access a session Storage object for the current origin.
The setItem() method takes 2 parameters - a key and a value and sets the key-value pair on the Storage object.
Note that the key and the value have to be strings.
If you need to store an array or an object, make sure to use the JSON.stringify() method to convert the value to a string before storing it in sessionStorage .
Copied!sessionStorage.setItem('tasks', JSON.stringify(arr));
The getItem() method takes a key as a parameter and returns the corresponding value.
If you previously stored a JSON string, make sure to use the JSON.parse() method to parse the value back to a native JavaScript object.
Copied!sessionStorage.setItem('tasks', JSON.stringify(arr)); console.log(sessionStorage.getItem('first')); // 👉️ bobby
You can open the Console tab in your developer tools to look at the output of calling the sessionStorage.getItem() method.
# sessionStorage vs localStorage in JavaScript
There are 2 very similar APIs that allow you to access the Storage object:
The main difference between the two is that:
- Data stored using sessionStorage is only valid for the particular Tab. When the tab is closed, the data is cleared.
- Conversely, localStorage has no expiration and is not cleared when the Tab is closed.
When you open multiple tabs/windows with the same URL, a unique sessionStorage property is created for each tab/window.
On the other hand, the localStorage property is shared by all tabs/windows with the same URL.
You can view your localStorage and sessionStorage variables by opening your developer tools ( F12 ) and selecting the Application tab.
You can expand the Local Storage or Session Storage dropdown menus in the left sidebar.
Each menu shows the currently stored key-value pairs.
To better understand the difference between session storage and local storage:
Copied!/** * Setting session variables */ sessionStorage.setItem('first', 'bobby'); sessionStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; sessionStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing session variables */ console.log(sessionStorage.getItem('first')); // 👉️ bobby console.log(sessionStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(sessionStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
- If you open the Application tab in your developer tools and click on Session Storage, you will see that the key-value pairs have been set.
- Now comment out the code or remove it.
- Close the browser tab and reopen it.
- If you open the Application tab in your developer tools and click on Session storage, you will see that the key-value pairs have been removed.
Data stored using sessionStorage is only valid for the particular Tab. When the tab is closed, the data is cleared.
# Using the localStorage property to access and set variables
Let's look at an example of using the localStorage property to access and set variables that are saved across browser sessions.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="id">bobbyhadz.comdiv> script type="module" src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!/** * Setting variables that are saved across browser sessions */ localStorage.setItem('first', 'bobby'); localStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; localStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing the variables */ console.log(localStorage.getItem('first')); // 👉️ bobby console.log(localStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(localStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
If I open the Console tab, I can see that the values are logged to the console.
You can also click on the Application tab and select Local Storage in the left sidebar.
As with the sessionStorage API, the setItem() method takes 2 strings - a key and a value.
If you need to store an array or an object in localStorage , make sure to stringify it.
Copied!localStorage.setItem('tasks', JSON.stringify(arr));
When you need to retrieve the data, make sure to parse it to a native JavaScript object.
Copied!const parsed = JSON.parse(localStorage.getItem('tasks'));
The benefit of using localStorage is that the data is preserved after you close the tab.
To better illustrate how this works:
Copied!/** * Setting variables that are saved across browser sessions */ localStorage.setItem('first', 'bobby'); localStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; localStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing the variables */ console.log(localStorage.getItem('first')); // 👉️ bobby console.log(localStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(localStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
- If you open the Application tab in your developer tools and click on Local Storage, you will see that the key-value pairs have been set.
- Now comment out the code or remove it.
- Close the browser tab and reopen it.
- If you open the Application tab in your developer tools and click on Local storage, you will see that the key-value pairs persist between sessions.
This is because localStorage has no expiration and is not cleared when the Tab/Window is closed.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.