I'm trying to build an SPA with PHP that has a static HTML skeleton and displays dynamic content inside a div called main_view, so far I've got it working to the point where the files actually do show the content that I want, but then another problem arose.. No JS executes from the inner files..
For example trying to call alert from the register.php file does nothing, regardless that the file actually shows it's contents in the index.php. Could you point me as to what I'm doing wrong?
This is the index.php section where the content should be displayed:
<main>
<div id="main_view" class="main_view">
</div>
</main>
This is the router.js file, which handles the dynamic content:
document.addEventListener("DOMContentLoaded", function() {
const path = window.location.pathname.split("/");
const file = (path[path.length-1].match(/^.*[^.php]/) || [])[0];
const isReload = !document.referrer || document.referrer === path;
//const lastVisited = sessionStorage.getItem("lastVisited");
//sessionStorage.setItem("lastVisited", window.location.pathname);
const isRoot = path === "/";
if (isRoot) {
loadPage("index", "");
window.history.pushState("", "", "/");
}
console.log(isRoot,document.referrer);
document.querySelectorAll(".main_nav").forEach((item) => {
item.addEventListener("click", function() {
const folder = item.getAttribute("folder") || "";
const path = item.getAttribute("file") || "";
if (path === 'index') {
window.location = "/";
}
console.log(folder,path,"das is select");
loadPage(path,folder);
if (path === "") {
window.history.pushState("", "folder", "/");
} else {
window.history.pushState("", "", path);
}
});
});
if (isReload) {
console.log("das is reload");
const menuItems = document.querySelectorAll(".main_nav");
const currentItem = Array.from(menuItems).find(item => {
return item.getAttribute("file") === file;
});
if (currentItem) {
const folder = currentItem.getAttribute("folder") || "";
const path = currentItem.getAttribute("file") || "";
loadPage(path, folder);
}
}
function loadPage($path, $folder = "") {
console.log($folder,$path,"das is load");
const main_view = document.getElementById("main_view");
const request = new XMLHttpRequest();
request.open("GET", $folder + "/" + $path + ".php");
request.send();
request.onload = function() {
if (request.status == 200) {
main_view.innerHTML = request.responseText;
}
}
};
});
......................................