I need some real help! I am getting an error when trying to pass JSON in PHP to Javascript with ajax!

I know this is a JS section, but I’m desperate.

I have JSON objects made in PHP and I want to pass them into JS with AJAX. I have followed a tutorial and I don’t know where I’ve gone wrong! Here is my code:

PHP (Auth.php): 
$userAuth->access = 1;
$userAuth->uid = $uid; 
$userAuthArray = json_encode($userAuth);

echo $userAuthArray;
JS (Auth.js):
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    const userAuth = JSON.parse(this.responseText);
    console.log(userAuth.access);
  }
};

xmlhttp.open("GET", "auth.php", true);
xmlhttp.send();

The error I am getting is this:

VM38:1 Uncaught SyntaxError: Unexpected token A in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.xmlhttp.onreadystatechange (auth.js:4)
xmlhttp.onreadystatechange @ auth.js:4
XMLHttpRequest.send (async)
(anonymous) @ auth.js:10

Thanks in advance, and apologies!
flugs

My guess is that you need to do,

echo json_encode($userAuthArray);

If you have an array and you echo it like so,

<?php

$myArray = ["This","is","my","array."];

echo $myArray;

The result will just be,

Array

I think that’s why you’re seeing the error, “Unexecpted token A in JSON at position 0.” It is getting to position 0, the first letter of the string, seeing an “A” and going, “Hey, wait that’s not JSON!”

However if you use the function json_encode() it’ll convert the output into something that can be read as JSON.

That hasn’t worked, it’s not an array thats just the variable name. It’s normal json $userAuth->access = 1; json_encode($userAuth);

Still getting the same error.

try console.log(this.responseText); as the FIRST line of your if statement, see what you’re actually getting returned from the PHP.