emjay emjay - 4 months ago 27
Ajax Question

How do I save a variable in php session after passing it cross domain via JQuery / AJAX?

Okay here's the deal.

I have two domains. Domain 1 hosts a main website with login sessions, Domain 2 hosts a chat.

So far, when logged in on domain 1, the chat link is visible.
When clicking the link on domain 1, a few things are meant to happen before going to domain 2. Domain 1 passes required info to pass.php on domain 2 via AJAX post.
domain 2 receives these variables, saves them to session and returns a message "ok" to domain 1.
If domain 1 receives a message equal to "ok" it means session was saved and go to domain 2. Else, print an error message saying chat can't load.

The data exchange is working between domains and domain 2 returns the "ok" message, but when the page "index.php" loads up and starts sessions, the session variable that was saved is empty. As if the variable was wiped on the other end just after the AJAX transfer. I want to keep what was stored in the session variable once I go to that page so I can use the session variables passed on from domain 1 on domain 2 accordingly.

here is the code from domain 1:

<ul class="dropdown-menu">
<li style="text-align:center;"><a href="member.php">Edit Profile</a></li>
<li style="text-align:center;"><a href="profile.php?user=<?php echo $username; ?>">View Profile</a></li>
<li style="text-align:center;"><a href="inbox.php?page=1">Messages</a></li>
<li style="text-align:center;"><a class="loadlink" id="chatclick" href="#">Chat</a></li>
</ul>

<script type="text/javascript">var name = "<?= $username ?>";</script>
<script type="text/javascript">var id = "<?= $userid ?>";</script>
<script src="/js/menuscript.js"></script>


Here is the menuscript file client side domain 1:

$(document).ready(function()
{
"use strict";
$('.loadlink').click(function(e){
e.preventDefault();
var lnk = 'http://52.39.48.172/index.php?test=test';

$.ajax({
url:"http://52.39.48.172/bin/pass.php",
data:"name="+name+"&id="+id,
type:"POST",
dataType:"json",
contentType:"application/json; charset=utf-8",
success:function(data)
{
if(data.callback == "ok")
{
window.location.href = lnk;
}
else
{
alert("ERROR: could not connect to chat");
}
}

});
});


});


This is the code for pass.php on domain 2

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

error_reporting(E_ALL ^ E_NOTICE);
session_start();



if(isset($HTTP_RAW_POST_DATA)) {
parse_str($HTTP_RAW_POST_DATA,$arr);



$_SESSION["username"] = $arr['name'];
$_SESSION["userid"] = $arr['id'];

$arr2['callback']= "ok";

echo json_encode($arr2);
}
else
{
$arr2['callback']= "nogo";
echo json_encode($arr2);
}


?>


and finally: This is index.php of domain 2

<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION["userid"];
$username = $_SESSION["username"];

if(!$username)
die("dead");

?>


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ram Chat</title>
<link rel="stylesheet" href="css/style.css" />

</head>

<body>
<div class="container">
<div class="chat" id="chatwindow"></div>
<div class="form">
<textarea name="message" id="messagebox" placeholder="Message: "><?php echo $username; ?></textarea>
</div>
</div>


<script src="js/app.js"></script>
</body>
</html>


Now when we switch from domain 1 to domain 2, we hit the "die("dead")" function on index php, because the session variable is not set, when it should be from the previous CORS communication. Instead the session variable remains empty.
Whats meant to happen is for the newly saved variable to appear in the "textarea"
when index.php loads on domain 2.

Can anyone please explain what I am doing wrong and how I should fix it?

Answer

I believe the session started in pass.php and the session in index.php are two different sessions. I cannot be sure since I don't have the means to try it out now but I've given a possible solution, do try and report back if it works for you or not. :)

pass.php

//...
if(isset($HTTP_RAW_POST_DATA)) {
    parse_str($HTTP_RAW_POST_DATA,$arr); 



    $_SESSION["username"] = $arr['name'];
    $_SESSION["userid"] = $arr['id'];

    $arr2['callback']= "ok";
    $arr2['sessid'] = session_id(); 

    echo json_encode($arr2);
}
//...

ajax

$.ajax({
     url:"http://52.39.48.172/bin/pass.php",
     data:"name="+name+"&id="+id,
     type:"POST",
     dataType:"json",   
     contentType:"application/json; charset=utf-8",    
     success:function(data)
     {
        if(data.callback == "ok")
        {                    
            window.location.href = lnk+"?sessid="+data.sessid;
        }
        else
        {
            alert("ERROR: could not connect to chat");
        }
     }

  });
 });

index.php

session_id($_GET['sessid']);
session_start();