4

On page load, I want to check if a PHP Session variable exists:

  • If it does, alert() the contents
  • If it doesn't, create it and save the current time

Here is my code:

$(document).ready(function(){

  <?php if(session_id() == '') { session_start(); } ?>

  if (!<?php echo isset($_SESSION['lbBegin'])?'true':'false'; ?>) {
    <?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
  } else {
    alert("<?php echo $_SESSION['lbBegin']; ?>")
  }

}); 

This code works in the sense that the first page load doesn't produce an alert() and a refresh shows the time, however every refresh / link click afterwards changes the time. I was expecting the time to stay the same during the entire session.

What have I done wrong?

4
  • Did you add session_start()? Commented Jan 18, 2016 at 10:56
  • add session_start() on top of your page. Commented Jan 18, 2016 at 10:57
  • You have a few mistakes. I have corrected them and posted the final code. Kindly have a look at my answer. :) Commented Jan 18, 2016 at 11:02
  • I don't know what you want to achieve, but mixing js and php code is clearly a bad idea, you should think about a better way of implementing client/server communication. Commented Jan 18, 2016 at 11:06

1 Answer 1

1

You need to add session_start() at the very beginning and check if a session variable exists. Do this way:

<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){

  if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
    // And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
    <?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
  } else {
    alert("<?php echo $_SESSION['lbBegin']; ?>")
  }

});
</script>

Correcting the AJAX Bit:

<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){

  if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
    // And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
    $.getScript("setTime.php");
  } else {
    alert("<?php echo $_SESSION['lbBegin']; ?>")
  }

});
</script>

Inside the setTime.php add the code:

<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.