This is the JS:
window.onload = function() {
let bodyContent = document.getElementById("appBody");
let jsonRequest = {
"loggedStatus":"check"
};
let jsonRequestString = JSON.stringify(jsonRequest);
let request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
let jsonResponse = JSON.parse(request.responseText);
if (jsonResponse.loggedStatus.localeCompare("true") == 0) {
document.getElementById("appBody").innerHTML = '<object type="text/html" data="HTML/calendar.html"></object>';
} else {
document.getElementById("appBody").innerHTML = '<object type="text/html" data="HTML/login.html"></object>';
}
}
}
request.open("POST", "PHP/Main.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("request=" + jsonRequestString);
}
and this is the php:
<?php
class Main {
protected $_path;
protected $_db;
protected $_session;
protected $_user;
public function __construct() {
include_once("dbconfig.php");
include_once("UserClass.php");
$this->_path = "/";
$this->_db = $connection;
$this->_session = (isset($_SESSION)) ? isset($_SESSION['user_id']) : false;
if ($this->_session) {
$user = new UserClass($this->_session, $this->_db);
$this->_user = $user->getUser();
} else $this->_user = false;
}
}
$main = new Main();
header("Content-Type: application/json; charset=UTF-8");
$request = json_decode($_POST['request']);
$response = array('loggedStatus' => 'true');
echo json_encode($response);
?>
So when I run this I see this error in the console:
Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.request.onreadystatechange (bodyLoad.js:10)
and basically, if I delete the "$main = new Main();" from the Main.php it all works perfectly and loads FirstExamplePage.html.
but I don't want to delete this, I intend to build this class to interpret the requests and return responses accordingly.
Anyone can point to why creating this object returns response to the js? Im not echoing nothing in the constructor, and even if I leave it blank it wont work, so Im assuming the creating new instances just automaticly uses some kind of response