1

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 ?

zac
  • 4,495
  • 15
  • 62
  • 127

4 Answers4

4

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' ] );
Community
  • 1
  • 1
Legotin
  • 2,378
  • 1
  • 18
  • 28
1

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.

Caio Ladislau
  • 1,257
  • 13
  • 25
0

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);
Jarlik Stepsto
  • 1,667
  • 13
  • 18
0

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.

Sudipta Kumar Maiti
  • 1,669
  • 1
  • 12
  • 18