To describe my question, I'am write 3 simple scripts:
- index.php (start a session and show html link);
- index.js (contain link click handler, fetch data from fetch.php);
- fetch.php (start a session, send response).
When I click on a link, javascript send a request to fetch.php. As I understand cookie also send because 'same-origin' specify. I'am expecting to see in response session_id, but response is appear after 7-9 seconds with message Failed to load response data. Why it can happened?
PS. If I remove session_start() line from fetch.php, response return instantly.
PSS. If I replace fetch with jQuery.post, response return instantly too.
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
<a href="/">request</a>
<script src="/index.js"></script>
</body>
</html>
index.js
let a = document.querySelector('a');
a.addEventListener('click', (e) => {
e.preventDefault();
fetch('/fetch.php', {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
credentials: 'same-origin',
body: JSON.stringify({
data: 'data',
}),
}).then((response) => {
console.log('Success');
}).catch((errors) => {
console.log('Error');
});
});
fetch.php
<?php
session_start();
header('HTTP/1.1 200 Ok', true, 200);
header('Content-Type: application/json');
echo json_encode(array(
'id' => session_id(),
));
?>