Reputation: 1821
I have seen a lot of people asking about the reverse, but what i need to do is store a string resulting from php script into localStorage?
Currently, my approach is to store the data in an attribute inside of an html element on my page like this:
<div id="php-data" data-php-value="<?= $var ?>"></div>
and then retrieve the value with JS and store it like this:
let phpVarStorage = document.getElementById("php-data");
let phpValue = phpVarStorage.getAttribute("data-php-value");
localStorage.setItem('php_var', phpValue);
I am just not thrilled with this approach, but I assume there are no PHP methods for storing data client side.
Can anyone offer another approach?
Upvotes: 1
Views: 1892
Reputation: 3875
Yes you can save it directly like this
localStorage.setItem('php_var', "<?=$var;?>");
Upvotes: 0
Reputation: 223
You can store directly like this, as long as you got PHP has this data with you in the same page
<script>
localStorage.setItem('php_var', "<?php echo $var;?>");
</script>
Upvotes: 3