How to Get Js Variable to Retain Value After Page Refresh

How to get JS variable to retain value after page refresh?

This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it.

When you need to set a variable that should be reflected in the next page(s), use:

var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);

And in any page (like when the page has loaded), get it like:

var someVarName = localStorage.getItem("someVarKey");

.getItem() will return null if no value stored, or the value stored.

Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify and JSON.parse. Technically, whenever you call .setItem(), it will call .toString() on the value and store that.

MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage isn't available.

It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).


References:

  • Browser Storage - https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
  • localStorage - https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorage
  • JSON - https://developer.mozilla.org/en-US/docs/JSON
  • Browser Storage compatibility - http://caniuse.com/namevalue-storage
  • Storing objects - Storing Objects in HTML5 localStorage

Keep a JavaScript variables value after a page refresh?

Cookies

The best solution is to use cookies. A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website (from Wikipedia).

Using a cookie you can save the state and later read it and use it.

With jQuery it is very easy to use cookies.

To set:

$.cookie("var", "10");

To get:

$.cookie("var")

To delete:

$.cookie("var", null);

Local Storage

When you want to save localy great amount of data, you have another opportunity — to use local storage (since HTML5). You can do it directly using JavaScript or using one of available jQuery plugins.

for example, with totalStorage:

var scores = new Array();
scores.push({'name':'A', points:10});
scores.push({'name':'B', points:20});
scores.push({'name':'C', points:0});
$.totalStorage('scores', scores);

How to initialize and keep value of updated js variable after page refresh using session storage?

You can use shorthand if else using this

team1score = sessionStorage.getItem('updatedScore1') ? sessionStorage.getItem('updatedScore1') : 0;

Object variable to retain value after page refresh besides session and cookie

You could serialise the object and store in localStorage. Then when you want to use it again, you unserialise it. Here's an example:

var myObject = {
"Hello": "World",
"Foo": "Bar"
}

localStorage.setItem("myObject", JSON.stringify(myObject));

Then later on, you can retrieve the object from localStorage:

var myObject = JSON.parse(localStorage.getItem("myObject"));

For more information, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

How to keep variable from POST after a page refresh?

You can save it in a session variable.

That way it should be accessible ad long as the session is alive.

// Start session
session_start();
// Your code
$myId = sanitize_key( $_POST['varPostId'] );
$myId = (int) $myId;
// If session value exist don't do anything
// If not save $myId as session variable
if(!isset($_SESSION["myId"])) $_SESSION["myId"] = $myId;

// Use session variable in query
query_posts(array(
'post__in' => array($_SESSION["myId"])
));

Just keep in mind the session_start. It needs to be started at every page you need to access the variable.



Related Topics



Leave a reply



Submit