I'm new with php and I'm trying to retrieve some data from a database in json encoding and then I want to retrieve the output with javascript. So I defined the following php functions in functions.php
:
<?php
function getConn(){
$USER='root';
$PASSWORD='mypass';
$HOST='localhost';
$DATABASE='dbname';
try {
$connection = new PDO("mysql:host=$HOST;dbname=$DATABASE", $USER, $PASSWORD);
return $connection;
} catch (PDOException $e) {
exit("Error: " . $e->getMessage());
}
}
function getData($connection){
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$connection->query("SET NAMES 'UTF8'");
$query = $connection->query("SELECT * FROM table;");
$results = $query->execute();
if ($results) {
$jobs = $query->fetchALL(PDO::FETCH_ASSOC);
header('Content-Type: application/json');
return json_encode($jobs, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else{
echo "ERROR <br>";
print_r($connection -> errorInfo());
}
}
?>
At this point, I have my main.php
, wich simply does:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('functions.php');
$connection = getConn();
echo getData($connection);
?>
If I go to the page http://localhost:5500/main.php
I can see the correct data, in correct Json format.
Client-side, I have an html page with the following javascript:
"use strict";
async function getData(){
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json; charset=UTF-8");
let res = await fetch("http://localhost:5500/main.php", myHeaders);
let data = await res.json(); // changed in: let data = await res.text();
console.log(data);
}
getData();
This code made error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
. So, I tried to log the response text and what is printed is the main.php
code.
Why does it happen? I expected the json to be retrieved which is the php output, instead of the php code.
Thanks in advance.
EDIT: since the question is marked as duplicated, I want to be clearer: the suggested answer is this, but my situation is different: my php code is executed. In fact, visiting the web page via chrome or firefox, I can display the php output as page text. What I can't do is to retrieve this output via javascript.