There are no tracking or monitoring cookies on this site. There are only cookies used for documentation examples related to cookies.
Close

Processing...
This may take a few seconds.

PHP SPA tutorial part 2

This is a continuation of the previous tutorial.

Well done for getting this far!

The rest of this tutorial consists of just setting up the PHP and HTML files, and as such is not really much of a tutorial. You need to just read and follow the code. Remember there is no frame-work with this, so the PHP is very simple.

None of the files are very difficult to understand, even if you do not know PHP. Look through each one and you will quickly find that out.

If you are following this tutorial exactly, you can skip this paragraph. If you are not following this tutorial exactly, and want to call dynamic PHP pages rather than static HTML, you would use the "page-output-json.inc.html" file instead of the "page-output.inc.html", and in your config, the data-ajax attribute in the page-list would be asking for the PHP file instead than the HTML file, so that part in the PHP code would need changing. That "page-output-json.inc.html" file shows you how to determine what content to show based on the Active CSS variables _ACSS and _ACSSTYPE, and also how to output a JSON string containing HTML.

The files below should be all you need.

It is assumed that you know what you are doing with basic PHP and web server setup, or some sort of alternative.

Step 7 - Create the server files

These files below should be created and populated with the specified content. You will need to have a web server set up for your development domain and PHP installed.

This website is produced. It's not pretty, but it shows all the elements you need. If you are wondering if there are any other files needed or PHP that you need to know for this, there isn't. It's pretty basic. We use nginx as the web server, as it is fast. But you can use Apache or Node or whatever web server you prefer.

When you have it working, inspect devtools and see what is happening to the menu elements when you rollover them. Because we have set up an ajax-pre-get on each link, the page will be retrieved ready for displaying when the menu button is clicked on - this happens in the background. But because of this, when you mouseover over the button you will see the classes and the attributes are inserted into the element. These are inserted before the ajax-pre-get runs. The link element now magically contains classes, and the actions for those classes in your config that tell the browser what to do, are ready for Active CSS to process in the event flow. Pretty simple technique, but it allows for tailored actions per link if you need to get complicated.

htdocs/about-me.php


<?php
// About me page. This is the first page that the web server finds.
$pageInclude = 'about-me';
$pageTitle = 'About me';

// Output the page.
include '../includes/page-output.inc.php';

?>
			

htdocs/blog.php


<?php
// Blog page. This is the first page that the web server finds.
$pageInclude = 'blog';
$pageTitle = 'Blog';

// Output the page.
include '../includes/page-output.inc.php';

?>
			

htdocs/index.php


<?php
// Index page. This is the first page that the web server finds.
$pageInclude = 'index';
$pageTitle = 'Welcome!';

// Output the page.
include '../includes/page-output.inc.php';

?>
			

htdocs/style.css


body {
	background-color: #576a7d;
	color: #fff;
}

h1 {
	text-align: center;
}

#content {
	max-width: 920px;
	margin: 0 auto;
}

a {
	font-size: 20px;
	color: chartreuse;
	text-decoration: none;
}

a:hover {
	color: #ccff9a;
}

.menu {
	margin: 20px 0 60px;
	text-align: center;
}

.menu a {
	display: inline-block;
	width: 100px;
	margin: 10px;
	padding: 10px 12px;
	background-color: lightgray;
	color: black;
	border-radius: 5px;
	cursor: pointer;
	text-decoration: none;
	pointer-events: auto;
}

.menu a:hover {
	background-color: lightslategray;
}
			

htdocs/activecss-config.txt


a:not(.outsideLink):not([target="_blank"]):click, form:not(.outsideLink):submit {
	prevent-default: true;
}

@pages {
	"/": data-title="My website" data-ajax="/html/index.html?v={$RAND}" class="myPage";
	"/index.php": data-title="My website" data-ajax="/html/index.html?v={$RAND}" class="myPage";
	"/blog.php": data-title="Blog" data-ajax="/html/blog.html?v={$RAND}" class="myPage";
	"/about-me.php": data-title="About me" data-ajax="/html/about-me.html?v={$RAND}" class="myPage";
}

.myPage:click {
	url-change: "{@href}" "{@data-title}";
	ajax: "{@data-ajax}" get html;
}

.myPage:mouseover {
	ajax-pre-get: "{@data-ajax}" get html;
}

.myPage:afterAjax {
	#content {
		quick-html: {$STRING};
	}
}
			

htdocs/activecss/activecss-2-5-0.min.js


// This should be the latest Active CSS core file.
			

htdocs/html/about-me.html


<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed euismod ultrices lacus, id interdum nunc vehicula non. Maecenas maximus ultricies mi id tempus. Integer eleifend nisi non nisl finibus, ut volutpat ipsum hendrerit. Phasellus tempus sapien vitae laoreet egestas. Aliquam id feugiat mi. Etiam justo leo, ornare vitae lobortis eget, placerat non arcu. Donec mollis orci ut odio tempor, eu consequat nunc varius. Donec id convallis augue. Suspendisse eget dui venenatis, rhoncus metus non, aliquam elit. Integer a odio sed tortor laoreet sagittis. Nulla urna est, pretium nec vulputate quis, vulputate a orci. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed tincidunt varius metus vitae pellentesque. Etiam semper, augue eu venenatis fringilla, enim purus ullamcorper tortor, non aliquet elit urna et lectus. Aenean quis sem tellus.</p>
<p>Vestibulum iaculis mollis nunc, ut tempor erat scelerisque non. Phasellus mattis in odio quis luctus. Mauris eget commodo diam, at lacinia lorem. Vivamus tincidunt nulla et nulla varius, et tincidunt est aliquet. Curabitur sed porttitor risus. Cras rutrum egestas convallis. Mauris id posuere eros. Vivamus euismod nisi et gravida bibendum. Ut nec malesuada purus. Morbi hendrerit suscipit purus ac pretium. Maecenas sed gravida lacus. Vivamus in porttitor neque. Donec vel suscipit felis.</p>
<p>Ut dignissim quam sed neque malesuada, ut fermentum felis molestie. Aliquam eget hendrerit libero. Donec pretium, mi ac finibus accumsan, erat tortor venenatis tortor, at mattis lectus neque sit amet mi. Pellentesque diam tortor, convallis eu nunc eget, cursus ultrices quam. Nullam tortor tortor, aliquam vitae ipsum vel, lobortis ultrices arcu. Sed eu ante non lacus elementum tristique vel et enim. Suspendisse scelerisque lectus hendrerit mauris gravida finibus. Nam ac blandit orci, nec tincidunt nunc.</p>
<p>Duis sed faucibus enim, et suscipit augue. Phasellus lobortis elit ex, sed varius enim gravida in. Mauris finibus velit sed ultricies tincidunt. Nullam viverra nisi enim. Sed accumsan quis turpis vitae sollicitudin. Mauris dignissim facilisis justo nec posuere. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas varius sit amet velit eu efficitur.</p>
<p>Pellentesque fringilla accumsan ante sit amet tincidunt. Nunc leo elit, mattis quis tellus sit amet, accumsan tristique enim. Morbi porta cursus commodo. Aenean eu purus sollicitudin, vulputate nisi sit amet, pellentesque nisi. Pellentesque placerat leo vel feugiat scelerisque. Aenean cursus viverra porta. Cras congue sem sem, non porttitor nibh tempus vestibulum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed mattis convallis elit vel dapibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam cursus dolor vel maximus pellentesque. Proin sed eleifend velit, sit amet dictum nisl. Vivamus cursus, velit vel euismod euismod, sem sem euismod velit, quis vestibulum est nisi at sapien.</p>
<p><a href="/blog.php">Random blog page link</a></p>
			

htdocs/html/blog.html


<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis auctor sem a molestie tincidunt. Maecenas quis lectus diam. Nulla facilisi. In ante sem, sollicitudin vel feugiat in, auctor ac nunc. Donec dapibus enim ac arcu porta, et eleifend turpis commodo. Suspendisse feugiat vestibulum blandit. In hac habitasse platea dictumst. Nullam luctus, lectus faucibus finibus bibendum, ante nisl sodales libero, quis sodales diam quam quis erat. Fusce ut tincidunt lacus. In eu elit nisl. Praesent ultricies pretium lectus, a congue lacus. Donec gravida urna magna, vel euismod velit dapibus mollis. Nulla maximus, eros eget interdum dignissim, est felis accumsan velit, non lobortis nisi diam eu libero. Pellentesque dictum placerat nisl sit amet semper.</p>
<p>Sed dolor augue, placerat eu consequat tempor, consequat vitae tellus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean ac augue tempor, convallis ex eu, hendrerit lacus. Suspendisse luctus nisi turpis, vel molestie diam faucibus ut. Ut eu mi hendrerit, eleifend nisl quis, cursus velit. Aenean fermentum euismod erat, et bibendum ante sagittis a. In egestas dui sit amet libero sollicitudin convallis. Vivamus ultrices volutpat ipsum a fermentum. In augue libero, egestas eget mi sit amet, semper aliquet nisl.</p>
<p>Nullam vitae laoreet arcu. Sed quis quam mi. Suspendisse sit amet semper eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam porttitor, velit blandit tempus efficitur, purus orci vulputate mauris, eu congue dui ante a lacus. Sed sollicitudin, enim non accumsan aliquam, nunc ante aliquam urna, et faucibus felis ligula nec ante. Aenean augue arcu, pellentesque sed sem quis, posuere bibendum odio. Mauris vulputate magna ut massa porta mollis. Cras consequat magna mattis massa accumsan rutrum. Quisque tristique, diam a iaculis venenatis, felis tellus vehicula quam, vel cursus orci eros vitae erat. Aenean imperdiet faucibus placerat. Duis mollis mattis orci, a ultricies mi ultricies quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ornare mauris a porttitor placerat. Donec nec eros tristique, cursus quam sit amet, pretium enim. Sed bibendum nisi non odio placerat ultrices.</p>
<p>Mauris rutrum nisi mauris. Curabitur ac tincidunt massa. Maecenas vitae efficitur arcu. Nullam luctus aliquam justo. Mauris consectetur orci vitae tincidunt posuere. Quisque blandit ex in quam vulputate viverra. Proin turpis dui, sollicitudin eget vulputate ac, rutrum sed ipsum. Cras maximus justo massa, ac tincidunt urna ullamcorper sit amet. Sed dapibus magna neque, id scelerisque neque dapibus quis. Donec euismod mollis purus et efficitur. Suspendisse congue pulvinar molestie. Pellentesque non risus ultricies, fermentum nibh ut, sodales elit. Aliquam consequat porta justo, ac porttitor turpis pellentesque nec. Curabitur at nulla tempor, pulvinar augue vitae, pulvinar urna. Nunc efficitur libero nunc, ac auctor orci rhoncus vitae.</p>
<p>Integer quis malesuada odio. Mauris tristique laoreet enim, in sollicitudin ligula. Morbi fermentum accumsan nunc a viverra. Nulla ut odio ut sapien tincidunt accumsan euismod in ligula. Cras sagittis metus quam, non aliquet est commodo vel. Duis leo nunc, rhoncus vestibulum ipsum eu, ornare placerat lectus. Nam sit amet neque ut eros efficitur semper at vitae turpis. Curabitur eu erat porttitor, bibendum mauris ut, ultrices leo. Quisque condimentum mauris eu lacus suscipit, facilisis faucibus mauris facilisis. Praesent enim turpis, rhoncus eu pellentesque eget, porta id nunc. Fusce dignissim quam sit amet mi mattis mollis.</p>
			

htdocs/html/index.html


<h1>Hello!</h1>
<p>This is my front page!</p>
			

htdocs/js/scripts.js


document.addEventListener('DOMContentLoaded', function(e) {
	ActiveCSS.init({
		configLocation: '/activecss-config.txt'
	});
});
			

includes/header.inc.php


<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo($pageTitle); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link defer rel="shortcut icon" href="/favicon.ico" type="image/png" />
<link defer rel="stylesheet" href="/style.css">
<script defer src="/activecss/activecss-2-5-0.min.js"></script>
<script defer src="/js/scripts.js"></script>
</head>
<body onclick="void(0);">
			

includes/menu.inc.php


<h1>PHP Single page website example 1</h1>

<div class="menu">
	<a href="/">Index</a>
	<a href="/about-me.php">About me</a>
	<a href="/blog.php">Blog</a>
</div>

<div id="content">
			

includes/page-output.inc.php


<?php
// Set the path for the html directory. We are already in the includes directory by this point.
set_include_path(__DIR__.':../htdocs/html/');

// Draw the *full* page (not the static HTML - this is grabbed straight from Active CSS).
include 'header.inc.php';
include 'menu.inc.php';
include $pageInclude.'.html';
include 'footer.inc.php';

?>
			

includes/page-output-json.inc.php


<?php
// Alternative page to page-output.inc.php if you have dynamic content and/or need to handle JSON strings.
// Draw the page.

set_include_path(__DIR__.':../htdocs/html/');

// Is this an ajax call? Set a handy variable to true or false.
$acss = (isset($_POST['_ACSS']) && $_POST['_ACSS'] == 1) ? true : false;
// Was there an ajax type sent over? If so, we'll set a variable for it.
$isJson = (isset($_POST['_ACSSTYPE']) && $_POST['_ACSSTYPE'] == 'JSON') ? true : false;

if ($acss && $isJson) {
	// This is an JSON-type ajax call - we will want all output to be in a string format.
	// Start the output buffer, which puts the output into memory rather than back to the browser.
	// We'll take the output out of the buffer later on, and then put it into a variable.
	ob_start();
}

if (!$acss) {
	// Not ajax - we need to show the whole page. Either refresh was hit or the URL was gone to directly.
	include 'header.inc.php';
	include 'menu.inc.php';
}

set_include_path(__DIR__.':../htdocs/html/');

// We always output the page contents at the very least.
include $pageInclude.'.html';

if (!$acss) {
	// Not ajax - we need to show the whole page. Either refresh was hit or the URL was gone to directly.
	include 'footer.inc.php';
}

if ($acss && $isJson) {
	// This is a JSON-type ajax call. We'll make a JSON array.
	$jsonArray = [];

	// Clean the output buffer and put the page data generated so far, it will be a string, into an item in an array.
	$jsonArray['result'] = ob_get_clean();

	// Convert the array to a JSON string, as we can't sent an array to the front-end. We need it in JSON format as a string.
	$jsonString = json_encode($jsonArray);

	// Tell the front-end that all is ok.
	http_response_code(200);

	// Send back the results.
	// In this case, it will be found as {result} on the front-end in Active CSS.
	// (if it isn't done by this JSON way, the ajax variable will be {$STRING}.)
	echo($jsonString);
	flush();

}

// That's it. The page has been sent to the front-end.
// If there was an ajax call but it was in HTML format, not JSON, then the contents has already been sent.

?>