I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.
When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)
I used both head tag and onload method to place the setCookie()
function. But result was same.
I used this jQuery library to write cookie.
Here's code I used to read and write the cookie.
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
background: #666666;
}
</style>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript">/script>
<script>
setCookie();
function setCookie() {
console.log('on Load');
var data_spl = $(location).attr('href').split('#?camlist=')[1];
if (data_spl != undefined) {
var len = data_spl.split(',').length;
$.cookie("len", len);
console.log($.cookie("len"));
} else {
console.log('undefined');
}
}
</script>
</head>
<body>
<?php
for ($i = 0; $i < 100; $i++) {
echo "<script>console.log('START');</script>";
echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
echo $_COOKIE['len'];
echo "<script>console.log('END');</script>";
}
echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
?>
</body>
</html>
EDITED:
I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.
var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
if (retparams.has) {
console.log('sucessfuly sent the paramlen!');
} else {
alert("can't read camarauids for grid making");
}
}, 'retparams');
set_session.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
$_SESSION['urllen'] = $_POST['params'];
echo json_encode(array('retparams' => 'has'));
echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
echo json_encode(array('retparams' => 'error'));
}
?>
Then I try to read the session value ($_SESSION['urllen']
) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)