Asked  7 Months ago    Answers:  5   Viewed   4.4k 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");
Saturday, May 29, 2021
answered 7 Months ago

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>
Wednesday, March 31, 2021
answered 9 Months ago

What if two clients process images at the same time?

You can try adding session_write_close() between setting the new status in the session, so that the new session data is stored, otherwise it will only get stored once your script finishes.

Another solution would be to save the status in memcache or to use a database, perhaps separate the statuses with a userid or creating an md5 hash on the image data

Wednesday, March 31, 2021
answered 9 Months ago

Here's an example that doesn't require jQuery:

function loadJSON(path, success, error)
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
            } else {
                if (error)
    };"GET", path, true);

Call it as:

         function(data) { console.log(data); },
         function(xhr) { console.error(xhr); }
Thursday, June 3, 2021
answered 7 Months ago

This is an Access-Control issue, not an ajax issue.

When you visit the url from your browser directly, you are requesting a (session) cookie from the domain you are visiting. When you are using ajax, in this case, you are requesting a cookie from a domain that is not the domain you are visiting.

On your php API file at, try this.

header('Access-Control-Allow-Credentials: true');

Then on your ajax request file, use the xhrFields parameter like so.

    url: '',
    xhrFields: { withCredentials: true },
    success: function(data) {

Now as long as you are calling the request from the origin, cookies will behave as expected.

Wednesday, November 17, 2021
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :