jeudi 5 février 2015

Session variable life cycle with server side generated javascript in PHP


I have a client's project that I'm adding in some modifications to.


On the template php page for the website I'm trying to:



  • Check for a message in the session variable

  • If the message exists, write it into a variable for the javascript I'm constructing

  • Clear out the session variable holding the message


Here's the javascript I'm constructing in my php page:



<script type="text/javascript">
$(document).ready(function (){
debugger;
var sessionMessage = <?php

if(isset($_SESSION['sessionMessage'])){
$sessionMessage = $_SESSION['sessionMessage'];
echo '"' . $sessionMessage . '"';
$_SESSION['sessionMessage'] = null;
} else {
echo "null";
}
?>;

if( sessionMessage !== null ){
alert(sessionMessage);
}
});
</script>


The problem I run into stems from the line:



$_SESSION['sessionMessage'] = null;


If I include this line to clear out the session message the javascript variable sessionMessage will always be set to null from the else statement. I verified that it was being set from the else by replacing the echo in the else with other text and the else is most definitely firing.


If I'm grabbing the value from the session on the line $sessionMessage = $_SESSION['sessionMessage']; and then using the $sessionMessage variable in the echo, why would the $sessionMessage variable be effected by the clearing of the session variable?


EDIT


The start_session(); line is in a file that gets included at the top of the php page that this javascript is rendered on. The file is not conditionally included so the session definitely starts every time this page is hit.


Also, I can add the following line directly after the <?php tag for the line var sessionMessage = <?php...:



die('<pre>' . var_dump($_SESSION['sessionMessage']) . '</pre>');


And this will print my sessionMessage successfully so the variable is definitely getting set.


Also also, if I take out the $_SESSION['sessionMessage'] = null; line the message will display ALL of the time which is more confirmation that it's getting set correctly, I just can't "forget" it correctly :/



and when/where your $_SESSION['sessionMessage'] was set ?



$_SESSION['sessionMessage'] is set in a file that uses a header("Location:/") to redirect the user to the page I'm working on. Basically, if I throw an exception on any page within the project, I'm setting a session message, redirecting to the home page, using the javascript above to grab the message, clearing out the session variable, and then popping up an alert with the session message.





Aucun commentaire:

Enregistrer un commentaire