Hello friends a newbie question. I am new to programming hence please be gentle.
I am trying to post multiple session variables using JavaScript so that I can use them later in my PHP at multiple places.
My index.php file
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
if ((empty($_SESSION['function1Val'])) & (empty($_SESSION['function2Val'])) && (empty($_SESSION['jsStatus']))) {
echo '<script type="text/javascript" src="vals.js"></script>
<script type="text/javascript">
var session=false;
var jsStatus;
var function1Val;
var function2Val;
</script>';
} else {
echo '<script type="text/javascript">
var session=true; var jsStatus=' . $_SESSION['jsStatus'] . ';
var session=true; var function1Val=' . $_SESSION['function1Val'] . ';
var session=true; var function2Val=' . $_SESSION['function2Val'] . ';
</script>';
}
?>
</head>
<body>
<?php
echo $jsStatus;
echo $function1Val;
echo $function2Val;
session_destroy ();
?>
</body>
</html>
My vals.js file
window.onload = function() {
// if there is no session (session = false)
if (!session) {
// Set value to variable jsStatus
jsStatus = 'enabled';
// Call function to get function1
function1();
// Call function to get function2
function2();
// Make ajax call to php page to set the session variable
setSession();
}
}
function function1() {
// code to get value goes here
function1Val = 'result1';
}
function function2() {
// code to get value goes here
function2Val = 'result2';
}
function setSession() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","session.php?function1Val=" + function1Val,true);
xmlhttp.send();
// like this I want to transfer other values of 'function2Val' and 'jsStatus'
}
My session.php file
<?php
session_start();
// check if it is already set if you like otherwise:
$_SESSION['function1Val'] = $_REQUEST['function1Val'];
$_SESSION['function2Val'] = $_REQUEST['function2Val'];
$_SESSION['jsStatus'] = $_REQUEST['jsStatus'];
?>
I know the code is messy but I don't know how to write the correct syntax. I actually tried to modify a single variable code but failed. hence need help.
The idea is to post various values derived out of various JavaScript functions to the session for use by PHP.
Please help.
UPDATE:
It has to be this way as the values to the said variables can be calculated with the help of JavaScript only.