Sunday, May 6, 2018

javascript alert for changing php variable




I have a $_SESSION created in php. One of its values is the last activity stamp.
I'd like to show the stamp on the

element on the page.



The $_SESSION['LAST_ACTIVITY'] is being updated in php part of the code, and according to the console output, I can see it is changed correctly:



$action = $_POST['action'];

switch ($action) {
case 'login': DoLogin(); break;
case 'logout': DoLogout(); break;
case 'update': updateSessionActivity(); break;
default: $errmsg_arr[] = 'Unknown action'; $errflag = true;
}

function updateSessionActivity()
{
if (isset($_SESSION['LAST_ACTIVITY'])) {

$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
}
echo "Session updated: ".$_SESSION['LAST_ACTIVITY'];
}
?>


The previous php function is being called from jQuery with $ajax when switching between the nav pane tabs, posting to php page and getting the $_SESSION parameter updated (I can see it in network response correct after echo Session updated).



However the

element's html with ID "page_header_cont" gets updated only once (first time I switch to another tab pane) and never changes after, although I continue to switch between the tabs and see that POST works correctly with variable updated.










What am I missing, why the php echo returns the same value for the variable? Tried in several browsers, thought it is some sort of cache issue, even tried to echo time(). The same output. First time works correctly, then ceases to update.



Edit
I was asked to edit the question to specify how it differs from what supposed to be the same questions.
I would like to point at the fact that the answer and question provided as duplicate are way too differ from the problem in my question.
I do have php code executed while surfing on the page and I DO have my variables changed. Now after the answer I have them also changed on the front page and they are not "hardcoded", whatever that means.


Answer



This line won't change between ajax calls:



$("#page_header_cont").html(" Last activity: " + ""



You should replace the php code by the data you receive in the ajax response.



To set an initial value, you can "write" a javascript variable and take the value from there in $(document).ready();



To do this, at the bottom of the body, you can set:






Then you can get the initial value from myPhpVrs.lastActivity, and any update from the ajax response.



Aditional note: Consder escaping php code to avoid javascript injection.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...