I am using PHP and I have Javascript object called "row" in one page that contain some data and I know how to pass it to another page using localStorage
but I wonder can I read this JS object using PHP functions in the second page ?

- 4,495
- 15
- 62
- 127
4 Answers
You can store your object in cookie instead of localStorage.
Cookie can store only strings, so you should encode your object to string with javascript JSON.stringify
, and then use json_decode
to decode it in PHP.
See here how to set cookie with javascript.
Here's an example:
var data = {/*your data*/},
string_data = JSON.stringify( data );
setCookie( 'my_data', string_data );
and then in PHP:
$data = json_decode( $_COOKIE[ 'my_data' ] );
-
error setCookie is not defined, please modify your example – zac Jan 18 '16 at 19:00
-
I used `document.cookie` – zac Jan 18 '16 at 19:10
-
`setCookie` is an abstract function to show the general idea – Legotin Jan 18 '16 at 19:33
You could use:
json_decode(string $json)
See documentation in http://php.net/manual/en/function.json-decode.php This takes a JSON encoded string and converts it into a PHP variable.

- 1,257
- 13
- 25
What exactly are you trying to do?
PHP itself is not able to read js objects or variables, but you can pass them to php through post/get request via ajax (for example).
To pass a js object to php use json.
In js:
JSON.stringify(j);
in php:
json_decode(json);

- 1,667
- 13
- 18
set localStorage
or sessionStorage
using javascript and retrieve values using javascript, no server code can directly access it.
Page1:
if(typeof(Storage) !== "undefined") {
localStorage.setItem("YourKey", "Your Value");
//replace "Your Value" with 'row' object
} else {
console.log("No Web Storage support..");
}
if(typeof(Storage) !== "undefined") {
sessionStorage.setItem("YourKey", "Your Value");
//replace "Your Value" with 'row' object
} else {
console.log("No Web Storage support..");
}
Page2:
if(typeof(Storage) !== "undefined") {
localStorage.getItem("YourKey");
} else {
console.log("No Web Storage support..");
}
if(typeof(Storage) !== "undefined") {
sessionStorage.getItem("YourKey");
} else {
console.log("No Web Storage support..");
}
stringify row
object using JSON.stringify()
and send the value to php either through query string or cookies or form post.

- 1,669
- 1
- 12
- 18