Reputation: 28128
I'm generating JSON data in PHP and loading it using AJAX. I only want to return JSON when a PHP session variable (auth
) is set during the login process.
getjson.php
<?php
session_start();
if(!isset($_SESSION['auth'])){
// code that sends an error back
} else {
// code that sends json back
}
?>
app.js
fetch("getjson.php")
.then(res => res.json())
.then(data => { // code that renders the data })
.catch(e => {
console.log("Error " + e)
})
When I open getjson.php
directly in the browser, the session check works. The json is only shown when the user is logged in.
But when I fetch getjson.php
using ajax, the session is not recognised and php always returns the error message.
How can I check a session before sending data that is fetched using ajax?
Upvotes: 0
Views: 697
Reputation: 161
It sounds like the browser is not sending the session cookie across to the server. You might be able to verify this by inspecting the HTTP request. If on Chrome, in Developer Tools, check the "Network" tab, select the request, then view the "Headers" tab, and look for "cookie:" under Request Headers.
I found this seemingly related article around the "fetch" API; does that help? https://github.com/github/fetch/issues/349
Upvotes: 3