SQL -> JSON -> HTML not displaying on InfinityFree

Website URL

http://bookrecommendationsystem.infinityfreeapp.com/book_display.html

Error Message

(please share the FULL error message you see, if applicable)

Other Information

(other information and details relevant to your question)

Hiya, I have the following PHP and HTML files. The PHP file accesses data from a MySQL database in the server and outputs it to JSON and then the HTML files displays this json data in a grid system. The files work in Replit when accessing a different database not on the InfinityFree server but won’t work when transferred to the InfinityFree server. I can currently print out the SQL database contents so the access to the server is not the issue but I’m currently getting ‘Error: Object’, which is incredibly vague, when running the html file.

<?php

$servername = "sql305.infinityfree.com";
$username = "if0_35349896";
$password = "OYHF6DQIyE5l8";
$dbname = "if0_35349896_books";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to fetch data
$sql = "SELECT item_name, item_author, image_url FROM `TABLE 1`;";
$result = $conn->query($sql);

// Fetch data as associative array
$data = array();
if ($result) {
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            // Handle null values
            foreach ($row as $key => $value) {
                if ($value === null) {
                    $row[$key] = ''; // Replace null with an empty string
                }
            }
            $data[] = $row;
        }
        // Set the content type to JSON
        header('Content-Type: application/json');
        // Output the JSON data
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    } else {
        echo "No data found.";
    }
} else {
    echo "Error: " . $conn->error;
}

// Close the connection
$conn->close();
?>

type or paste code here

<!DOCTYPE html>
<html>
<head>
    <script src="js/jquery-3.7.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: auto auto auto;
            padding: 10px;
        }
        .grid-item {
            padding: 20px;
            text-align: center;
        }
    </style>
</head>
<body>

<div class="grid-container" id="grid-container">
    <!-- Data will be inserted here -->
</div>

<script>
    $(document).ready(function () {
        $.ajax({
            url: 'book_fetcher.php',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                const gridContainer = $('#grid-container');
                $.each(data, function (index, item) {
                    const gridItem = $('<div class="grid-item"></div>');
                    const image = $('<img>');
                    image.attr('src', item.image_url);
                    image.attr('alt', item.name);
                    image.css({'width': '100px', 'height': '100px'});
                    const name = $('<p></p>').html('<b>Name:</b> ' + item.name);
                    const author = $('<p></p>').html('<b>Author:</b> ' + item.author);
                    gridItem.append(image, name, author);
                    gridContainer.append(gridItem);
                });
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    });
</script>

</body>
</html>

Please change your hosting account password immediately! When posting code to the forum, always make sure that any sensitive information like your password is redacted.

3 Likes

I have updated the password to your hosting account to a new random password. Please keep in mind that this is a public forum, so anything you post here can be seen by anyone. So you must make sure to never share any confidential data, which especially includes passwords.


As for the issue itself, I checked your page, and in both the Network tab and the Console tab in the browser Developer Tools, I see the book_fetcher.php page responds with a 500 Internal Server Error. This usually means that the PHP code crashed. I don’t see anything immediately wrong with it, but this is how you can start troubleshooting it yourself:

6 Likes

Thank you for changing the password - I won’t do that again! The 500 error only appears, however, because you changed the password and when you update it in the book_fetcher.php code and then run the php file I get no errors. Unfortunately, there is also no json output either, which I think I want. The following code works, albeit with the new password, which makes me think the php is OK:

<?php

$servername = "sql305.infinityfree.com";
$username = "if0_35349896";
$password = "OYHF6DQIyE5l8";
$dbname = "if0_35349896_books";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to fetch data
$sql = "SELECT * FROM `TABLE 1`";
$result = $conn->query($sql);

// Fetch data and generate HTML table
if ($result->num_rows > 0) {
    echo "<table border='1'>
    <tr>
    <th>Id</th>
    <th>Item Name</th>
    <th>Item Author</th>
    <th>Image URL</th>
    </tr>";
    // Output data of each row
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['item_name'] . "</td>";
        echo "<td>" . $row['item_author'] . "</td>";
        echo "<td>" . $row['image_url'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
// Close the connection
$conn->close();
?>

Did you enable display errors?

What are you trying to do here?

1 Like

I can view errors on the console if that’s what you mean?

Sorry, I wasn’t very clear. The latter code is just a demonstration to show I can access the SQL database contents and do something with them. What I actually want to achieve is to use the first two code snippets to access the database and then display the contents in a grid on a browser

No.
Read the article about the 500 error again. You need to enable display errors in order to see PHP errors.

3 Likes

When I check the endpoint again, I see it responds with a 200 OK status code (meaning the code ran without errors), but the response is completely empty. The Content-Type header is set to application/json, so we know it doesn’t reach any error conditions.

This means that this line is returning nothing:

echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

It could be that JSON serialization fails, in which case json_encode will return false. It might also be that $data is not populated correctly.

Maybe it’s possible to check this with some var_dump lines in there?

5 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.