Load Backend Data JS and PHP
Load Backend Data Dynamically Using JavaScript and PHP
Watch the full tutorial here:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="./main.js" defer></script>
<title>fetch data</title>
</head>
<body>
<header>
<span>logo</span>
<nav>
<a href="#" data-page="home">home</a>
<a href="#" data-page="about">about</a>
<a href="#" data-page="contact">contact</a>
</nav>
</header>
<div id="content">
<!-- content display here... -->
</div>
</body>
</html>
css
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
header {
width: 100%;
height: 50px;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 15px;
& nav {
display: flex;
flex-direction: row;
align-items: center;
gap: 15px;
}
}
javascript
document.addEventListener("DOMContentLoaded", () => {
const links = document.querySelectorAll("nav a");
const contentDiv = document.getElementById("content");
links.forEach(link => {
link.addEventListener("click", (e) => {
e.preventDefault();
const page = link.getAttribute("data-page");
fetch(`server.php?page=${page}`)
.then(res => res.text())
.then(data => {
contentDiv.innerHTML = data;
})
.catch(error => console.error("Error loading the page: ", error));
});
});
fetch(`server.php?page=home`)
.then(res => res.text())
.then(data => {
contentDiv.innerHTML = data;
})
});
php
<?php
$page = $_GET['page'] ?? "home";
$pages = [
'home' => '<h2>Welcome to the homepage</h2> <p>Home content...</p>',
'about' => '<h2>About us</h2> <p>Information about the company...</p>',
'contact' => '<h2>Contact</h2> <p>Our contact form...</p>',
];
echo $pages[$page] ?? "<h2>404 Page not found</h2>";