christopher.web christopher.web - 25 days ago 9
Javascript Question

Variable is undefined when returning to previous page

I'm having issues getting a variable to not be undefined. Basically when I go to another page and then click back on the browser, the variable goes undefined and the script stops working. However it does work on the initial load if I refresh the browser.

//player admin callback
function getPlayerAdmin(admin_callback){
var admin_data = false;
var formData = {
'player_id' : $('#post-v').attr('data-val')
};

$.ajax({
type: 'post',
url: '/popins/player/controls',
data : formData,
dataType : 'json',
success: function(data) {
admin_callback(data);
},
error : function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
}
});
}

//load youtube videos
function loadPlayerVideos(){
var player_id = $('#post-v').attr('data-val');

//get admin
getPlayerAdmin(function(output) {

console.log(JSON.stringify(output));

if(output.controls.is_admin == true){
admin_data = true;
}else{
admin_data = false;
}
});
}


The data returned is:

{"controls":{"is_admin":true}}


My problem is that I get an 'Uncaught ReferenceError: admin_data is not defined'.

Would anyone know why the variable goes undefined?

Thanks!

Answer

I had the same issue before. I think this is not a browser problem (we're talking about sessions, that is read only server side, on the client you just have the token to indentify what is your session).

Guess when you go back the server code is not being executed (the browser has the page cached and will only load assets like images or javascript). You can improve the behavior doing that kind of checking client-side with localStorage

Example:

 localStorage.setItem('is_admin', 'true'); 

And then in the page1, you add this client-side:

 if(localStorage.getItem('is_admin') === 'true'){

 } 

This one should work just fine. Hope it helps!