Codementor Events

Displaying Database Content on a Web Page Using HTML, CSS, and JavaScript

Published Mar 20, 2024
Displaying Database Content on a Web Page Using HTML, CSS, and JavaScript

To read data from a database and display it on an HTML page using HTML, CSS, and JavaScript, you typically need to use a server-side language like PHP, Node.js, Python (with Flask or Django), or any other backend technology to interact with the database. However, I'll provide a basic example using JavaScript for the frontend and a mock data source.

Assuming you have a simple database with some data, you'd typically use an API to fetch that data from the frontend. For the sake of this example, we'll use a mock API endpoint that returns JSON data.

Here's how you can do it:

  1. HTML file (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display Data from Database</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Data from Database</h1>
<div id="data-container"></div>

<script src="script.js"></script>
</body>
</html>
  1. CSS file (styles.css):
/* styles.css */
body {
  font-family: Arial, sans-serif;
}

.container {
  margin: 20px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.data-item {
  margin-bottom: 10px;
}
  1. JavaScript file (script.js):
// script.js
document.addEventListener('DOMContentLoaded', function() {
    fetchData();
});

function fetchData() {
    // Assuming you have an API endpoint that returns JSON data
    fetch('https://example.com/api/data')
    .then(response => response.json())
    .then(data => {
        displayData(data);
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
}

function displayData(data) {
    const dataContainer = document.getElementById('data-container');
    
    // Clear existing data
    dataContainer.innerHTML = '';

    // Iterate over the data and create HTML elements to display it
    data.forEach(item => {
        const dataItem = document.createElement('div');
        dataItem.classList.add('data-item');
        dataItem.textContent = `ID: ${item.id}, Name: ${item.name}, Age: ${item.age}`;
        dataContainer.appendChild(dataItem);
    });
}

In this example:

  • The HTML file (index.html) contains the basic structure of the webpage.
  • The CSS file (styles.css) styles the HTML elements.
  • The JavaScript file (script.js) fetches data from a mock API endpoint and dynamically creates HTML elements to display the data on the webpage.

Replace the API endpoint in the fetchData() function with the actual endpoint that fetches data from your database. The displayData() function formats and displays the fetched data on the webpage.
Message me for more details...Ace

Discover and read more posts from Anthony Elam
get started
post commentsBe the first to share your opinion
Show more replies