1

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

Deanz
  • 13
  • 4
  • `Unexpected token < in JSON at position 0` usually means your php is outputting html (probably an error page). Check the result of the php thoroughly in your browser dev tools. – IncredibleHat Mar 15 '18 at 21:23
  • If you're not specifically echoing anything, the `<` may come from an error. If you have xdebug on, errors/notices/warnings/ etc. will be HTML formatted. – Don't Panic Mar 15 '18 at 21:23
  • `console.log(jsonResponse)` **before** you try to parse it as JSON. What you get? – Paolo Mar 15 '18 at 21:52

1 Answers1

0

First of all you shouldn't include other php files in the constructor. It's better to use PSR autoloader. Secondly, you use session without starting it with session_start().

The problem comes for sure from the fact that you output something that is not json and you specify in the header that it's json and also you use JSON.parse which also expect JSON.

To make it work you need to handle the problem with output. You can do it on multiple ways.

  1. You should define and fix the error that causes the problem. For example by looking at "network" tab of developers tools in the browser and seeing the actual response
  2. You should use error_handler to present the errors formatted in JSON. See http://php.net/manual/en/function.set-error-handler.php
  3. You could use output buffering to prevent these problems. See http://php.net/manual/pl/function.ob-start.php
  4. Even if you don't echo anything there are situations that f.e because of wrong file coding the bytes are sent to the browser. Like UTF-8 BOM. See How to fix "Headers already sent" error in PHP for more info

With all these steps you should be able to provide proper JSON.

Robert
  • 19,800
  • 5
  • 55
  • 85
  • Thank you all so much! The problem originated from another class where I used multiple constructors (not knowing php doesnt allow that) and your 1st remark, using the dev tools was what cleared it up for me, I didn't knew I can check responses from all pages there! Ill go over all the links you provided anyway to learn some more. – Deanz Mar 16 '18 at 08:21
  • You're welcome, if this answer satisfy you then you can accept it with "check" icon, this makes the question closed. Moreover, on stackoverflow you can always upvote/downvote answers even if you're not the owner of the question. – Robert Mar 16 '18 at 08:52