Reputation: 445
I have a file called index.php. With script tags, it references index.js.
I also have a file called payment.php. With script tags, it references payment.js.
I need to set a variable called seatSelected in index.js and then use it in payment.js. However, I do not want to reference index.js in payment.php.
I have tried to make a file called globals.js, reference it in index.php before index.js containing the following:
var selectedSeat;
function setSelectedSeat(seat){
selectedSeat = seat;
}
function getSelectedSeat(){
return selectedSeat;
}
And setting the value in index.js with:
setSelectedSeat("test");
Receiving it in payment.js with (referencing globals.ks in payment.php above payment.js):
alert(getSelectedSeat());
But it alerts 'undefined'. Am I doing something wrong? How can I reference this variable without referencing the file it is changed in?
Upvotes: 0
Views: 136
Reputation: 306
You are trying to persist the state of variables while transitioning from one page to another and your application seems to have data that would require session expiry, I suggest you use sessionstorage
. With help of polyfills you can give sessionstorage
support till IE6
browser.
SessionStorage
over LocalStorage
But Remember with sessionstorage
you can only store strings key-value
pattern. And you need to use JSON.stringify
and JSON.parse
method to store your complex objects in browser memory.
Here you can find a list of polyfills that you can use to provide the support of sessionstorage in non supporting browsers : https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#web-storage-localstorage-and-sessionstorage
Also you can read the following article to understand sessionstorage
and localstorage
in a better way: http://diveintohtml5.info/storage.html
Upvotes: 1
Reputation:
You cannot access variables created from another page.
You could use localStorage
with cookies
as fallback.
function setSelectedSeat(seat){
if(localStorage) {
localStorage['selectedSeat'] = JSON.stringify(seat);
}
else {
//add code to store seat in cookie
}
}
function getSelectedSeat(){
if(localStorage) {
return JSON.parse(localStorage['selectedSeat']);
}
else {
//add code to retrive seat in cookie
}
}
Upvotes: 1