im trying to get PHP operate well with javascript. I have looked on internet and put all the solution inside at once but none work. I want to create a cross-site AJAX request but i cant seem to be able to have session_start() stick.
I have this PHP code on server:
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: null");
if (isset($_SESSION))
{
$_SESSION["time"] = time();
if (isset($_SESSION["time"])) echo json_encode("Session exists:" .$_SESSION["time"]);
}
else
{
echo json_encode("Session does not exist!");
session_start();
}
?>
I have this JavaScript(jQuery) code on client:
$(function()
{
$(".action").on("click", call);
});
function call()
{
$.ajax({
url: "http://localhost/api.php",
method: "POST",
data: [],
async: true,
dataType: "json",
xhrFields: { withCredentials: true },
crossDomain: true,
processData: true,
headers: {"accept": "application/json"},
cache: true,
success: function(result)
{
console.log(result);
},
error: function(e)
{
console.error(e);
}
});
}
No matter how many times i push the button i get "session does not exist"
Is there a way I can let PHP and jQuery establish safe session between each other and sort all the necessary session cookies by themselves? I can't use <?php var_dump($_SESSION); ?> because not every user will be a website.