I
I
Ibishka2020-08-01 15:26:18
PHP
Ibishka, 2020-08-01 15:26:18

Why does ajax return null?

I have 2 projects, 1 is a React front and 2 is a PHP backend. The back has a logged.php file in it

session_start();
echo json_encode($_SESSION['logged']);

Initially, I put the value "user" in the session for the test
; when I switch to it, it says "user" everything is buzzing.
But when I make a fetch request on it, it returns null
What is the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-08-01
@Ibishka

session_start() either starts a new session or resumes an existing one. For the second option, php needs to know the session ID, which is either stored in cookies (PHPSESSID) or passed as a url parameter. In the case of a fetch request, you pass neither the first nor the second, so php starts a new clean session with the logged variable undefined.
https://www.php.net/manual/ru/session.examples.bas...

N
Nadim Zakirov, 2020-08-01
@zkrvndm

When sending a request to a different domain, fetch does not pass cookies, and without cookies, your server cannot determine the user. More details here:
https://learn.javascript.ru/fetch-api#credentials
You need to set the credentials parameter to include , and for the server to work correctly, your server must return the Access-Control-Allow-Credentials header .
By itself, this is only if your site and backend are on different domains. If they are on the same domain, but the error persists, look for the cause on the server or try using XMLHttpRequest first .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question