Viewed   4.8k times

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.

 Answers

1

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");
Tuesday, November 29, 2022
 
3

Make sure that you use

session_start();

In the start of every page, or any PHP file that needs to have access to the session.

The easiest way to do this, is have something like a header.php file and include/require this at the top of every page of your site or common pages.

In this header.php you would have something like

<?php
    session_start();
    if (isset($_SESSION['username'])) {
      // This session already exists, should already contain data
        echo "User ID:", $_SESSION['id'], "<br />"
    } else {
        // New PHP Session / Should Only Be Run Once/Rarely/Login/Logout

        $_SESSION['username'] = "yourloginprocesshere";
        $_SESSION['id'] = 444;
    }
?>

The simply have your page like this

 <?php require "header.php"; ?>
 <!doctype html>
 <head></head>
 <body>
 <?php
     if (isset($_SESSION["username"])) {
         $loggenOnUser = $_SESSION["username"];
         echo "Found User: ", $loggenOnUser, "<br />"
     } else {
         $loggenOnUser = " a public user";
     }
 ?>
     <div class="gridContainer clearfix">
         <div id="div1" class="fluid">
             This page is being called by my login.php file.
         </div>
         <div id="LoggedInUser" class="fluid ">
             Hi.  I'm <?php echo $loggenOnUser; ?> 
         </div>
         <img id="homeImage"  src="images/home.gif" /> </div>
     </div>
 </body>
 </html>
Friday, October 28, 2022
5

Creating & Accessing the Session Variable using JavaScript

Creating Session Variable using JavaScript

<?php session_start(); ?>
<html>
<head>
<script type='text/javascript'>
    function setSession(variable, value) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "setSession.php?variable=" + variable + "&value=" + value, true);
        xmlhttp.send();
    }
</script>
</head>
<body>
<?php
    if(isset($_SESSION['login']) && $_SESSION['login'] == "true")
      echo "Session Active. <a href="javascript:setSession('login', 'false')"><input type='submit' value='De-Activate'></a>";
    else
      echo "Session Inactive. <a href="javascript:setSession('login', 'true')"><input type='submit' value='Activate'></a>";
      echo "<a href="index.php"><input type='submit' value='Re-Load Page'></a>";
?>
</body>
</html>

Assigning value to it

<?php
    session_start();
    if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
    {
        $variable = $_REQUEST['variable'];
        $value = $_REQUEST['value'];
        $_SESSION[$variable] = $value;
    }
?>
Friday, August 26, 2022
 
2

Put this between <HEAD> and </HEAD> put this:

<script src="jquery-2.0.2.js"></script>
<script>
$.customPOST = function(data,callback){
  $.post('search.php',data,callback,'json');
}

$(document).ready(function() {
    $(".search").keyup(function(){
        $.customPOST({search: $.('#searchid').val(),function(response){
         if(response.success){
          var html_code  = '<div class="show" style="text-align:left;">';
              html_code += '<span class="name">' + response.final_username + '</span>';
              html_code += '&nbsp;<br/>' + response.final_email + '<br/></div>';
          $("#result").text(html_code);
          $("#result").show();
         }
    });

});
</script>

You PHP script must return a JSON response like this way :

<?php
... your code here and ....

$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);

// here we create and return our JSON response
$response = array('final_username' => $final_username, 'final_email' => $final_email);
echo json_encode($response);

?>
Monday, December 12, 2022
 
lamak
 
3

you are getting if from request not session.

It should be

session.getAttribute("MyAttribute")

I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.

${sessionScope.MyAttribute}

or

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<c:out value="${sessionScope.MyAttribute}" />

you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.

Read more

  • Oracle Tutorial - Using JSTL

  • Oracle Tutorial - Expression Language

Friday, August 19, 2022
 
medmik
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :