To describe my question, I'am write 3 simple scripts:
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(),
));
?>
Problem is appear only in Chrome. The solution is to add intermediate json handler into fetch
}).then(function (response) {
return response.json();
}).then(function (json) {
console.log('Success');
console.log(json);
}).catch(function (errors) {
console.log('Error');
});
and problem pass away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With