Anjali Madas Anjali Madas - 6 months ago 41
Javascript Question

jQuery REST Session doesn't work, but works in POSTMan

I am trying to build a PHP Based REST API, but I am stuck with this issue. I have got

session_start()
in PHP code and a simple Sign In, Sign Out script, which accepts the same
username
and
password
to be authenticated:

<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
$message = array();
if ($_GET["action"] == "signin") {
if (count($_POST) && isset($_POST["username"]) && isset($_POST["password"]) && $_POST["username"] == $_POST["password"]) {
$message["user"] = $_POST["username"];
$message["success"] = true;
$_SESSION["user"] = $message["user"];
} else {
unset($message["user"]);
$message["success"] = false;
unset($_SESSION["user"]);
}
} elseif ($_GET["action"] == "signout") {
session_destroy();
$message["success"] = true;
} elseif ($_GET["action"] == "whoami") {
$message["success"] = true;
$message["user"] = isset($_SESSION["user"]) ? $_SESSION["user"] : "Guest";
}
die(json_encode($message));
?>


And I am using POSTMan (Chrome Extension) to login and check and everything works fine. But when I use my jQuery's
$.getJSON()
and
$.post()
methods, when I try
action=whoami
, I am just getting
Guest
. My jQuery code:

$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest. Okay! :)
$.post("http://localhost/api.php?action=signin", {
username: "admin", password: "admin"
});
// Gives me success with the user logged in.
$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest Again! :O


I have already tried the same thing using POSTMan and it worked charm. But using jQuery this didn't work. So, I tried using:

$.ajaxSetup({
cache: false
});


Nevertheless, I also tried appending a random string like this, but same response:

Not this as well. Can someone please help me proceed? This is a show stopper for me.

$.getJSON("http://localhost/api.php?action=whoami");
// Gives Guest. Okay! :)
$.post("http://localhost/api.php?action=signin", {
username: "admin", password: "admin"
});
// Gives me success with the user logged in.
$.getJSON("http://localhost/api.php?action=whoami&kill=cache");
// Gives Guest Again! :O

Answer

Generally sessions are stored in Cookies. So, when you are making Cross-Domain requests, Cookies are not shared. A simple fix would be using a proxy.php but now I got the best solution as to use named sessions.

Use the following code to get your sid:

<?php
  if (isset($_GET["sid"]))
    session_start($_GET["sid"]);
  else
    session_start();
  header("Access-Control-Allow-Origin: *");
  header("Content-type: application/json");
  var_dump(session_id()); // Gives you the SID.

From the next time, use the sid as a GET parameter, and that will check the server session and resume the session.

Comments