Reputation: 509
Let's start with a typical PHP/html/JavaScript environment. Skipping past the <head>
and <body>
suppose we have:
<script>
var foo = <?php echo generateFoo(); ?>;
</script>
Let's suppose this is working perfectly in every way, except for one minor flaw. That is, whenever I navigate away from the page and click "back", I get the old value of foo
rather than an updated one.
I understand this error. Clicking "back" loads the page from the cache, not the server, so it returns to the previous value of PHP, not the current one. However, I want it to force update. (This is especially important because the user could be changing the value on another page, and someone who isn't an expert in html would expect "back" to take you to an updated version of the previous page. Code is always easier to change than user behaviour.)
What can I write that will function exactly like the code above, but will also execute when the user navigates back?
(I think the correct solution may use AJAX, but maybe I'm wrong. The page already uses AJAX from a jquery CDN, so I may as well make use of it if I can.)
Edit:
A solution that allows caching but just updates that one variable would be ideal. However if stopping caching is the only solution, I don't even know how to do that. So telling me how to do that would be good.
Copied directly from my code without alteration:
<?php
...
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0 ");
?>
So yes, I have already tried to stop caching. It isn't working in the BFCache.
Upvotes: 2
Views: 124
Reputation: 369
Check out this thread and the code example:
window.addEventListener("pageshow", function (event) {
var historyTraversal = event.persisted ||
(typeof window.performance != "undefined" &&
window.performance.navigation.type === 2);
if (historyTraversal) {
// Reload the page.
window.location.reload();
}
});
Upvotes: 3