0

I am trying to fetch data from a MySQL database and display it (currently just logging it due to the error).

The error is : SyntaxError: Unexpected token < in JSON at position 0

My PHP code connecting to the database:

<?php

$conn = mysqli_connect('localhost', 'root', '', 'mywholeheart');

$sql = mysqli_query($conn, "SELECT * FROM `products`");

$result = mysqli_fetch_all($sql, MYSQLI_ASSOC);

exit(json_encode($result));

?>

My JS code that has the fetch request:

fetch('server.php')
.then((res) => res.json())
.then(response => {
    console.log(response)
})
.catch(error => console.log(error));

Almost every video or post on this topic has to do with spelling the place you're fetching the data from which is not what I am struggling with. They also suggest logging it as text but all that does is display my PHP code.

Does anyone know why I might be getting this error and how I would go about fixing it? I am not using any libraries or frameworks at this moment.

1 Answers1

2

Your server doesn't execute .php files. It just get it as a text file. what the error says about < character, it is actually the first character of your text file. So that's the real problem here.

Soroush Bgm
  • 482
  • 2
  • 15