Reputation: 143
I have a multidimensional array ($order).
echo json_encode($order); produces the output below so that you can see the structure:
[{"rank":5,"day":1},{"rank":4,"day":1},{"rank":1,"day":2},{"rank":3,"day":2},{"rank":2,"day":2}]
I'm storing it in localStorage which I think is correct?
var array = "<?php echo(json_encode($order)); ?>";
localStorage.setItem('array', array);
a) How do I retrieve it from localStorage?
b) And then how do I use it in php?
Upvotes: 0
Views: 1465
Reputation: 53626
localStorage stores strings, not structured objects. If you want to store a JSON object, use localStorage["mything"] = JSON.stringify(myvar)
, and then to retrieve it from localStorage (which is bound to individual pages), use JSON.parse(localStorage["mything"])
on the same page.
Not using JSON.stringify means you'll be storing the string "[Object object]" or something similar, because JavaScript will coerce your object into a string and get it completely wrong for your purpose.
Upvotes: 1
Reputation: 93
this line:
var array = "<?php echo(json_encode($order)); ?>";
is producing a string:
var array = "[{"rank":5,"day":1},{"rank":4,"day":1},{"rank":1,"day":2},{"rank":3,"day":2},{"rank":2,"day":2}]";
but the string will break because of nested quotes.
the line should be written with single quotes:
var myArray = '<?php echo(json_encode($order)); ?>';
now you will have a proper string to store into localstorage with:
localStorage.setItem('myArray', myArray);
you can then retrieve it from localstorage with:
myArray = localStorage["myArray"];
But then, as totymedii suggests, your best bet for using the array in php is to send it to your server in an ajax call.
-C
Upvotes: 0