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.

 Answers

94

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
 
Gilko
answered 7 Months ago
34

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

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
 
oroshnivskyy
answered 9 Months ago
98

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)
                    success(JSON.parse(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

Call it as:

loadJSON('my-file.json',
         function(data) { console.log(data); },
         function(xhr) { console.error(xhr); }
);
Thursday, June 3, 2021
 
laurent
answered 7 Months ago
83

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 api.example.com, try this.

header('Access-Control-Allow-Origin: example.com');
header('Access-Control-Allow-Credentials: true');

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

  $.ajax({
    url: 'https://api.example.com',
    xhrFields: { withCredentials: true },
    success: function(data) {
      console.log(data)
    }
  });

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

Wednesday, November 17, 2021
 
Pointy
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 :
 
Share