0

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.

ma4strong
  • 300
  • 2
  • 8
  • If you check your server logs you will undoubtedly see an error explaining why your script was not executed. Removing `myHeaders` from your fetch request should make it work. For starters, the second parameter to fetch would need to be an object which has a `headers` property, you cannot supply the instance of Headers directly. Secondly, you do not even need to set that header at all, you are getting json, not sending it. The server should be the one setting the content-type header, not the client. – Besworks Jul 06 '22 at 18:35
  • I did it because I found it on the web, looking for a solution but it doesnt work. This means that, even if I remove that `myHeader`, it doesn't work. As I said, I'm new with php and I don't know how to log. Thanks for the hints. – ma4strong Jul 07 '22 at 08:51
  • The location of your php error log will vary depending on the server software and operating system. You can find it by checking the **Environment** section in the output of [`phpinfo()`](https://www.php.net/manual/en/function.phpinfo.php) – Besworks Jul 07 '22 at 13:08
  • I changed the line `error_log = /path/to/home/php_errors.log`, but no file is created when I execute my js code. – ma4strong Jul 07 '22 at 14:05
  • Aside from the headers problem I mentioned before, there doesn't seem to be any issues with your code. You need to do some troubleshooting with a bare minimum test case and work out your configuration issues. You will probably have better luck finding help with this over at the [webmasters](https://webmasters.stackexchange.com/) site. Some things to consider before posting a question there: Did you restart the service after changing the log path? Did you specify a real path or literally use `/path/to/home/`? Does your web service user have access to write to the specified path? – Besworks Jul 07 '22 at 15:21
  • I'm currently using the VScode live server for php. I closed and restarted it after changing log path. Sure i specify a real path: it was my Desktop path. With the command `ps aux | egrep '(apache|httpd)'` I can see the user whose home I specified in the log path, then it should have write permission. – ma4strong Jul 07 '22 at 15:37
  • https://docs.devsense.com/en/vs/debugging/output – Besworks Jul 07 '22 at 18:48
  • I'm not using this server because it requires Windows OS. I'm currently working on Ubuntu. I'm using [PHP Server](https://github.com/brapifra/vscode-phpserver) – ma4strong Jul 08 '22 at 09:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/246272/discussion-between-ma4strong-and-besworks). – ma4strong Jul 08 '22 at 09:47

0 Answers0