如何在没有页面刷新的情况下在javascript中捕获php会话变量?
I have an index.php
, where I do session_start()
etc. For login, I send an ajax request to receiver.php
, where I set the session variables etc and get an ajax response back.
Now, I can perfectly capture the php session variables only when I refresh the index.php
page that has the following code:
jsSessionUserId = <?php
if (isset($_SESSION['userId'])) { //LoggedIn:
echo json_encode($_SESSION['userId']);
} else { // Not logged in.
// some code here
}
?>;
What I really want is to put this in a function and then call this function when I receive a successful ajax response (and thus not have the need to refresh the index.php
page). It is not working. I suspect that the php doesn't quite work inside of a javascript function. Grateful for any help.
It is bad idea to mix things up. Like php and javascript. Easiest solution for you right now - overwrite your javascript variables once successful login response is received.
$.post("receiver.php", formData, function(response){ // login callback
if(response.UserId){ // return user id if login is successful
jsSessionUserId = response.UserId; // overwrite old variable
}
}, "json");