I have PHP server on my localhost. And file with following script:
?php
include 'config.php';
$mysqli = new mysqli(GGC_HOST , GGC_USER , GGC_PASSWORD , GGC_DB);
if (mysqli_connect_errno()){
die("Connect failed: ". mysqli_connect_error());
}//if
$mysqli->set_charset("utf8");
$queryString="SELECT Id, name, description, price, old FROM fruits;";
$myArray=array();
if ($result = $mysqli->query($queryString)) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$myArray[] = $row;
}//while
}//if
echo json_encode($myArray);
$result->close();
$mysqli->close();
?>
When I try to run my php file in browser, it gives me some result, like this:
[{"Id":"1","name":"\u10d5\u10d0\u10e8\u10da\u10d8","description":"\u10d1\u10e0\u10dd\u10ea\u10d9\u10d8 I \u10ee\u10d0\u10e0\u10d8\u10e1\u10ee\u10d8\u10e1","price":"1.25","old":"0"},{"Id":"2","name":"\u10db\u10e1\u10ee\u10d0\u10da\u10d8","description":"\u10d2\u10e3\u10da\u10d0\u10d1\u10d8 \u10d5\u10d0\u10dc\u10d8\u10e1","price":"3.5","old":"0"}]
My first question is: Why it shows it so strange in browser, and how to fix it?
when I fetch data from JavaScript:
fetch('http://localhost/aaa/fruits.php', {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, cors, *same-origin
headers: {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin":"*"
// 'Content-Type': 'application/x-www-form-urlencoded',
},
// Useful for including session ID (and, IIRC, authorization headers)
})
.then(response => response.json())
.then(data => {
console.log(data) // Prints result from `response.json()`
})
.catch(error => console.error(error))
Console shows me:
SyntaxError: Unexpected end of input at index.js:156
I can't solve this problem during 3 days and decided to share with you. 156th line is:
.then(response => response.json())