Set Session Variable Using JavaScript in PHP

Set Session variable using javascript in PHP

In JavaScript:

jQuery('#div_session_write').load('session_write.php?session_name=new_value');

In session_write.php file:

<?
session_start();

if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>

In HTML:

<div id='div_session_write'> </div>

How can I set session variable with JavaScript

Please try it if you want to use session using jquery
First include jquery-1.9.1.js and jquery.session.js

$(document).ready(function(){ 
$('.button').click(function(){
var href = $(this).val();
$.session.set("yoursessioname", "storevalue");
})
});
alert($.session.get("yoursessioname"));

more detail http://phprocks.letsnurture.com/create-session-with-jquery/

How to access php SESSION variable in javascript

<?php $session_value=(isset($_SESSION['id']))?$_SESSION['id']:''; ?>
<html>
<head>
<script type="text/javascript">
var myvar='<?php echo $session_value;?>';
</script>
<script type="text/javascript" src="general.js"></script>
</head>
<body>

</body>
</html>

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:

 <script type="text/javascript">
function SetUserName()
{
var userName = "Shekhar Shete";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
function GetUserName()
{

var username = '<%= Session["UserName"] %>';
alert(username );
}
</script>

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{x.innerHTML="Geolocation is not supported by this browser.";}
}

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=" + position.coords.longitude, true);

httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState == 4 && httpRequest.status == 200)
{
// Handle the response here. Show error or success message or whatever...
}
};

httpRequest.send(null);
}

Then on your php script you can set the values to the session, verifying it and verifying the values(of course).

Note: It's been a century I don't write ajax in pure JS. Please warn me for errors.

UPDATE:

I have fixed the way of using the callback of getCurrentPosition according to this and this documentation.

UPDATE 2:

You can use the common way to send that data to database with a form. Forget everything above and try this:

Suposing you have a form like this:

<form method="post" action="set_positions.php" id="form1">
<input type="text" id="inputField3" />
<input type="text" id="inputField4" />
</form>

Try this JS code:

function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}

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.

Here is the HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
<label for="websites1">Websites</label>
<select name="websites1" id="websites1">
<option value="Design">Design</option>
<option value="Dev">Dev</option>
<option value="Ecom">Ecom</option>
</select>
</form>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
<script type="text/javascript">

$(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;

});

});

</script>
</body>
</html>

Here is the AJAX part:

//pass_value.php

<?php session_start();

$_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();

?>

EDIT 1:

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.

EDIT 2:

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="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.

Main.php

<body>
<input type="hidden" value="$SESSION_['user_id']" class="user_id">
<script src="login.js"></script>
<script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']

</body>

postad.js

$(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.

Main.php

<body>
//content..

<script>
var user_id = "<?php echo $SESSION_['user_id'] ?>";
</script>
<script src="login.js"></script>
<script src="postad.js"></script> // console.log(user_id); that file you'll get that id.
</body>


Related Topics



Leave a reply



Submit