saving variable value and retrieve it after page refresh [duplicate]

I have a string value saved in to a variable, my webpage auto reloads after a certain process.. I need to know if I can get the value stored in that variable even after page refresh?

Im refreshing my web page using javascript code window.location.reload()

If not will it work if I take to server side script like php?

Answers:

Answer

JavaScript:

1) localStorage (HTMl5 browsers only) - you could save it as a property of the page's local storage allowance

2) save it in a cookie

3) append the variable to the URL hash so it's retrievable via location.hash after the refresh

PHP

1) save it as a session variable and retrieve it over AJAX each time the page loads

2) save it in a cookie (might as well do the JS approach if you're going to cookie it)

Any PHP approach would be clunky as you'd have to first send the value of the variable to a PHP script over AJAX, then retrieve it over AJAX after reload.

Answer

You can store this as a $_SESSION variable.

session_start();

$myVar = null;

// some code here

if (!isset($_SESSION['myVar'])) {
    $_SESSION['myVar'] = "whatever";
} else {
    $myVar = $_SESSION['myVar'];
}
Answer

You will have to persist this variable in a Cookie/Webstorage/Session. Web pages are stateless.

Answer

yes you could save your variable on server side as session value or on client side in localstorage (or as a cookie)

Answer

Cookies are your friend:

// Set a cookie or 2
document.cookie = 'somevar=somevalue';
document.cookie = 'another=123';

function getCookie(name)
{
    // Cookies seperated by ;   Key->value seperated by =
    for(var i = 0; pair = document.cookie.split("; ")[i].split("="); i++)
        if(pair[0] == name)
            return unescape(pair[1]);

    // A cookie with the requested name does not exist
    return null;
}

// To get the value
alert(getCookie('somevar'));
Answer

Using javascript you can store that variable into a cookie (the user must have cookies enabled), and then retrieve the cookie after.

The approach is something like this:

To save:

function setCookie(c_name,value)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + 1);
var c_value=escape(value);
document.cookie=c_name + "=" + c_value;
}

To retrieve:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Ref: http://www.w3schools.com/js/js_cookies.asp

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.