qadenza
qadenza

Reputation: 9293

how to keep js variable value accross multiple php pages

index.js // linked to all php files.
var pass;
console.log(pass); // undefined

$("#btn").click(function() {
    pass = "323";
    location.href = "test.php";
});

going to test.php console.log shows again undefined.
I need to keep pass value as 323 accross all pages, once it is estblished.

Upvotes: 0

Views: 63

Answers (2)

Manish Jangir
Manish Jangir

Reputation: 5437

You can use the session to get your things work smoothly on all pages.

var pass;
console.log(pass); // undefined

$("#btn").click(function() {
   pass = "323";
   $.post('savesession.php','pass='+pass,function(){
       console.log("session saved");
       location.href = "test.php";
   });
});

savesession.php

<?php
session_start();
$pass = $_POST['pass'];
$_SESSION['pass'] = $pass;

anypage.php

<?php
session_start();
$pass = $_SESSION['pass'];

Upvotes: 1

maowtm
maowtm

Reputation: 2012

Simplest method: Use localStorage.

If you only need to store strings:

var pass = localStorage.pass;

$("#btn").click(function() {
    pass = "323";
    localStorage.pass = pass;
    location.href = "test.php";
});

Or, notice that localStorage will change all things you store in into string. So if you wanted to store object, numbers, etc, you need JSON.stringify.

// index.js
if (localStorage.pass === undefined)
    localStorage.pass = "null";
var pass = JSON.parse(localStorage.pass);

$("#btn").click(function() {
    pass = "323";
    localStorage.pass = JSON.stringify(pass);
    location.href = "test.php";
});

Upvotes: 1

Related Questions