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