5

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?

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Da Silva
  • 229
  • 1
  • 7
  • 17

6 Answers6

7

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.

Mitya
  • 33,629
  • 9
  • 60
  • 107
6

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'];
}
Matt
  • 6,993
  • 4
  • 29
  • 50
0

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

madflow
  • 7,718
  • 3
  • 39
  • 54
0

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

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0

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'));
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
0

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

dmmd
  • 2,938
  • 4
  • 33
  • 41