I am trying to retrieve the data from database. Whatever data I retrieve, I put that data into array and then apply json_encode($data). I successfully get Array of Objects in the response as a text. But when I try to JSON.parse(response) I get an error which which says unexpected token [.
First I thought that the data will be already parsed so I tried console.log(response[0]) in order to print the first object, but the result was [. I don't know what's the problem.
My question might be same to others, but I tried all possible solutions, and couldn't solve it through those answers.
My PHP code :
public
function showDeposits($db_conn) {
$sql = "SELECT * FROM `deposit`";
if ($db_conn - > query($sql)) {
$r = $db_conn - > query($sql);
if ($r - > num_rows > 0) {
$data = array();
for ($i = 0; $i < $r - > num_rows; $i++) {
$data[] = $r - > fetch_assoc();
}
echo json_encode($data);
}
}
}
My Javascript code :
this.depositForm = function() {
var form = document.querySelector("#dep_form");
form.addEventListener("submit", function(e) {
e.preventDefault();
var json = {
time: getTime().text,
stamp: getTime().stamp,
date: getDate().dateText,
data: JSON.parse(toJSONString(this))
};
fetch("model.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(json)
}).then(function(t) {
t.text().then(function(res) {
var j = JSON.parse(res);
console.log(j);
})
})
})
}
The response

console.log(res)at the bottom there - sounds like it's not valid JSON.{"success":true}should not be at the beginning there - remove whatever's adding it and things might work.