3

i am new to PHP and i am ajax with PHP, i am getting the result from server but my JSON is not parsable.

here is my PHP code:

<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');

require 'connection.php';
$ReturnObject = (object) [
    'error' => false,
    'errorMessage' => "",
    'data' => "1"
];

echo json_encode($ReturnObject);

?>

and my javascript:

$.ajax({
                dataType: 'text',
                url: serverUrl + "test.php",
                type: "POST",
                data: { email: "" },
                success: function (data) {
                    JSON.parse(data);
                    alert("Thank you for subscribing!");
                },
                error: function (requestObject, error, errorThrown) {
                    alert("There was an error. Try again please!");
                }
            });

i get this error: Uncaught SyntaxError: Unexpected token  in JSON at position 0

but data is:

"{"error":false,"errorMessage":"","data":"1"}"

now after some time, i removed

require 'connection.php';

and pasted the code instead to become:

<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');

$servername = "localhost";
$database = "testMe";
$username = "Mika";
$password = "123123";


$conn = mysqli_connect($servername, $username, $password, $database); // Establishing Connection with Server..

if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
}

$ReturnObject = (object) [
    'error' => false,
    'errorMessage' => "",
    'data' => "1"
];

echo json_encode($ReturnObject);

?>

and with the same JS, it is parsing correctly with no errors. and the same data is returned:

"{"error":false,"errorMessage":"","data":"1"}"

am i doing something wrong with the require?? it is not the problem with the connection since it is successful and i can query the db

bjzero
  • 39
  • 2
  • What is the character shown in the error message ? `Uncaught SyntaxError: Unexpected token in JSON at position 0` Have you tried printing / logging `data` directly to see the actual value you are trying to parse ? – Seblor Dec 03 '19 at 11:07
  • `console.log(data)` is saying what ? Because `"{"error":false,"errorMessage":"","data":"1"}"` those quotes look weird as it is self closing. – robinvrd Dec 03 '19 at 11:07
  • I agree about the quote. They should not be there. Try removing your first and last quote, and your JSON will be bvalid. – M.Be Dec 03 '19 at 11:09
  • I assume *connection.php* is in the same directory? The actual *require* isn't failing is it? (since it's *require* it'll die with a fatal error if the path isn't valid, which would bork the JSON) – CD001 Dec 03 '19 at 11:28
  • @robinvrd `console.log(data)` is `{"error":false,"errorMessage":"","data":"1"}` – bjzero Dec 03 '19 at 11:29
  • @CD001 it's in the same directory, and i don't think it's failing, since i can query the db and get results – bjzero Dec 03 '19 at 11:32
  • 2
    Is there anything at *all* before the opening ` – CD001 Dec 03 '19 at 11:37
  • @Seblor it's empty space for some reason – bjzero Dec 03 '19 at 11:38
  • 2
    It's not an empty space, in the post there's `\ufeff` character (zero width no-break space) in the code and after the word "token ". You can see it when using a proper text editor, or ex. [at jsfiddle](https://jsfiddle.net/dkb5ex7v/1/). – Teemu Dec 03 '19 at 11:39
  • @Teemu you are correct, there's `\ufeff` character when i past it to notepad. and i found the problem to be, when pasting from visual studio, to the file editor in the server, `\ufeff` character is being added before ` – bjzero Dec 03 '19 at 11:47
  • 2
    Make sure you save your files as "UTF-8 without BOM" encoded. – Teemu Dec 03 '19 at 11:49
  • 2
    `\ufeff` ... and that's the `BOM` - *when pasting from visual studio* - thank MS for that one :| Remove that and you should be good. – CD001 Dec 03 '19 at 11:49
  • 1
    @CD001 yes you are correct, when pasting from visual studio to the file editor on the server it's adding the `\ufeff` character automatically at the start of the file. and now i removed it, and everything working normally. thank you – bjzero Dec 03 '19 at 11:50

1 Answers1

0

There should be no problem, expect when from some reason require 'connection.php' print some error, try to console.log(data), and make sure that the connection error is printed in JSON format right now die("Connection failed: "... will print just a string. So javascript can't parse it to JSON object.