Skip to Content

How to Create A Single Page Application with PHP

In this tutorial, we'll explore how to develop dynamic single-page applications using PHP, elevating user experience with seamless navigation and interaction. Say goodbye to page reloads and hello to pure web magic! Whether you're new to PHP or an experienced developer, this tutorial is your gateway to crafting captivating web experiences. Let's dive in!

What is a Single Page Application?

A single-page application (SPA) is a web-based platform that interacts with users by dynamically refreshing the existing page with updated data from the server, departing from the conventional method of loading entirely new pages in the browser.

The Code

PHP & HTML Code

We'll begin by creating a simple PHP page in the root directory of our project named index.php. We'll parse the request URI to determine which page we want to navigate to automatically. If a page name doesn't exist in the slug, we'll default it to home.

Next, we'll add three links in the top navigation section and a container for housing the page content. A quick PHP snippet will include the page the user is requesting to view. Finally, we'll establish a connection to our script file where all the action happens:

<?php
$request = explode("/", $_SERVER["REQUEST_URI"]);
$page = strtolower($request[1]);

if (!strlen($page)) {
$page = "home";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP SPA</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1" />
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>

<main>
<div id="content">
<?php include "page/" . $page . ".php"; ?>
</div>
</main>

<script src="js/main.js"></script>
</body>
</html>

Now, we'll create three pages in a sub-directory of our root named page and add the following files:

home.php

<h1>Home Page</h1>
<p>This is the home page.</p>

about.php

<h1>About Page</h1>
<p>This is the about page.</p>

contact.php

<h1>Contact Page</h1>
<p>This is the contact page.</p>

JavaScript Code

First, we'll explore the JavaScript functionality! We'll craft a personalized function called Navigate(), which takes a single parameter page representing the link to our PHP file. Leveraging JavaScript's inherent fetch() method, we'll dynamically load our PHP file and insert the retrieved contents into our designated content placeholder element:

function Navigate(page) {
let container = document.getElementById("content");

fetch("page/" + page + ".html")
.then(response => response.text())
.then(html => {
container.innerHTML = html;
})
.catch(error => {
console.error("Error fetching page: ", error);
}
);
}

Lastly, we'll set up an event listener for our navigation menu links to trigger a page load whenever a link is clicked. The page's name is extracted from the anchor tag's href attribute, excluding the preceding symbol. Then, our custom function is invoked to load the respective page. Finally, we use the pushState() function to automatically change the URL without page load, allowing users to navigate to a page, refresh the browser, and still remain on the same page:

document.querySelectorAll("nav a").forEach(link => {
link.addEventListener("click", function(event) {
event.preventDefault();

let page = this.getAttribute("href").substring(1);

Navigate(page);

history.pushState({}, null, page);
});
});

Configuration File

Now, we'll create a configuration file in the root directory of our project named .htaccess and include the following line:

ErrorDocument 404 /index.php

This is necessary because we're using friendly URLs to load our pages instead of loading the PHP file directly, and instructs Apache to load the index.php file by default if a page is not found.

Conclusion

That's all there is to it! You've mastered the art of building your single-page application with PHP, all with just a handful of code snippets!

The full code example is available in the GitHub repository, so you can clone and make changes to fit your application.

Created: March 30, 2024

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.