Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of php session_start() when javascript fetch

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(),
));
?>
like image 258
Evgeniy Avatar asked Sep 01 '25 22:09

Evgeniy


1 Answers

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.

like image 92
Evgeniy Avatar answered Sep 03 '25 10:09

Evgeniy