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.



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

Make sure that you use


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

    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>
     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 id="LoggedInUser" class="fluid ">
             Hi.  I'm <?php echo $loggenOnUser; ?> 
         <img id="homeImage"  src="images/home.gif" /> </div>
Friday, October 28, 2022

Creating & Accessing the Session Variable using JavaScript

Creating Session Variable using JavaScript

<?php session_start(); ?>
<script type='text/javascript'>
    function setSession(variable, value) {
        xmlhttp = new XMLHttpRequest();"GET", "setSession.php?variable=" + variable + "&value=" + value, true);
    if(isset($_SESSION['login']) && $_SESSION['login'] == "true")
      echo "Session Active. <a href="javascript:setSession('login', 'false')"><input type='submit' value='De-Activate'></a>";
      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>";

Assigning value to it

    if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
        $variable = $_REQUEST['variable'];
        $value = $_REQUEST['value'];
        $_SESSION[$variable] = $value;
Friday, August 26, 2022

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

<script src="jquery-2.0.2.js"></script>
$.customPOST = function(data,callback){

$(document).ready(function() {
        $.customPOST({search: $.('#searchid').val(),function(response){
          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>';


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

... 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

you are getting if from request not session.

It should be


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.



<%@ taglib prefix="c" uri=""%>

<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
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 :