Regarding on html5 pushState, when back button was clicked, url was able to reflect the changes required but div in-within did not able to show the old info, this also applies to forward button.
I am new to this, below is the codes:
index.php
<button type="button" id="menu-btn-1">Menu 1 (steak)</button>
<button type="button" id="menu-btn-2">Menu 2 (vegan)</button>
<div id="menu-res"></div>
<script src="./index.js" type="text/javascript"></script>
res.php
<?php
if($_POST['order'] == "steak"){
echo "medium rare steak";
}
if($_POST['order'] == "salad"){
echo "hawaii salad";
}
?>
index.js
function show(input) {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
console.log(this.responseText);
document.getElementById("menu-res").innerHTML=null;
document.getElementById("menu-res").innerHTML=this.responseText;
//how to maintain state when back/forward button is clicked?
history.pushState(this.responseText, null, input);
}
}
xmlhttp.open("POST","res.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
let data = 'order='+input;
xmlhttp.send(data);
}
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("menu-btn-1").addEventListener('click', ()=> {
show("steak");
});
});
window.addEventListener('DOMContentLoaded', function() {
document.getElementById("menu-btn-2").addEventListener('click', ()=> {
show("salad");
});
});
window.addEventListener('popstate', ()=> {
show("");
});
To use the stored "state" you need to use the
popstatelistener to render / process whatever data you have stored in the history stack. Taking much from your original code perhaps the following single-page script will help.The key to displaying the original content ( which is what I believe was the central point of your issue ) is the use of
setdisplay( e.state )within thepopstatelistener.