Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 845
Da Silva Avatar asked Jul 31 '12 12:07

Da Silva


2 Answers

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.

like image 134
Mitya Avatar answered Sep 27 '22 00:09

Mitya


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'];
}
like image 40
Matt Avatar answered Sep 24 '22 00:09

Matt