I have a multisite setup, where each site loads it's data via ajax. Everything is working perfect expect one detail. If I press the back button the ajax data is loaded from the browser cache an not from the server. This is problematic, since the user might navigate to a second page, changes a state and navigates back to the previous page where he want's to see the change in the overview (e.g. the accepted tasks chart now has one more accepted task because he accepted it).
The most common solution I found is adding a time stamp to the ajax request (in jQuery via the
cache: false
property). However this has the disadvantage that it disables the http caching (statuscode 304) which I don't want to do. Also I need the 304 statuscode to not update my view in other scenarios.The second option is binding the
window.onbeforeunload
and display a warning message when the user leaves the page. This invalidates the browser cache so the request is done (without adding a timestamp) even when the back button is pressed. The disadvantage is, that the user gets a confirmation dialog every time he navigates from the page (which is very annoying). For security reasons I can't confirm it via JavaScript, and if I don't display a message, the cache is not invalidated.
Are there more tricks to invalidate the broser cache /make sure the ajax request really goes to the server?
If someone want't to try it our, here is a sample code for the onbeforeunload
. In your network tracer tool (e.g Fiddler) you will se that the request is send to the server when the user navigates to the page with the back button. If you coment return 'Hello world';
you won't. (Note that you will see it in your browser debugger network tracer in both cases, but this is not represential for waht is actually send to the server).
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>onbeforeunload</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<a href="http://google.com">Link away</a>
<script>
window.onbeforeunload = function () {
return 'Hello world';
}
$.ajax({
type: "GET",
url: "test", //doesn't matter if it is invalid
success: function (data) {
}
});
</script>
</body>
</html>