Fetch Api cannot get session from PHP server

I am using Fetch Api in my application.

I have a PHP server page to retrieve session data that has already been defined previously. It looks like this:

<?php header('Content-Type: application/json; charset=UTF-8'); header('Access-Control-Allow-Origin: *'); session_start(); // $_SESSION['data'] already defined before $result = array(); // print_r($_SESSION['data']); if (isset($_SESSION['data'])) { $result = $_SESSION['data']; $result['code'] = 'ok'; } else { $result['code'] = 'error'; } echo json_encode($result, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); 

I also got another html page to get session data. It looks like this:

  <script> $(function() { // use $.ajax $.ajax({ url: 'session.php', dataType: 'json' }) .done(function(res) { console.log(res); }); // end // use fetch fetch('session.php').then(function(res) { if (res.ok) { res.json().then(function(obj) { console.log(obj); }); } }); // end }); </script> 

The problem is that when I use $ .ajax (), the session data can be displayed correctly. But when I use fetch (), the session data was undefined.

So what is wrong and how can I fix it? Thanks!

+5
source share
2 answers

If you want fetch send cookies, you must provide the credentials option.

See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters for more details.

+8
source

jquery ajax is a regular ajax request and the browser sends a cookie header with a session id that identifies your session.

fetch doesnt - instead a new session is created without any data send the php session id either with a url or with a header

take a look at: http://php.net/manual/en/session.idpassing.php

+1
source

Source: https://habr.com/ru/post/1247512/