I am using Fetch Api in my application.
I've got a PHP server page to get session data which was already defined before. It seemd 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 the session data. It seemd 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, when I use $.ajax(), session data can be correctly showed. But when I use fetch(), the session data was undefined.
So, what goes wrong and how can I fix it? Thanks!
REST API's are meant to be stateless. What that means is that each request from a client should include all the information needed to process the request. In other words, if you are writing a REST API in PHP then you should not be using $_SESSION to store data about the client's session.
Start a PHP Session A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Starting a PHP Session Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session. The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
If you want fetch
to send cookies, you have to provide the credentials
option.
See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters for details.
jquery ajax is a usual ajax request and the browser is sending the cookie header with the session id that identify your session.
fetch doesnt - instead a new session is created with out any data send the php session id either with url or header
have a look at: http://php.net/manual/en/session.idpassing.php
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