I've came across a problem with using a 'hashbang' to keep track of which page has been loaded via AJAX.
When a link is clicked which loads content through an AJAX request into the content div, the hash of the URL changes to the page name. For example, if the user comes directly to pageA (http://www.domain.com/pageA) and then clicks a link for pageB, the URL will change to http://www.domain.com/pageA#/pageB
I'm using CodeIgniter for my application, and the code which handles the hash changing is in my header view, and it does the following:
<script type="text/javascript">
window.redirect = function() {
if(window.location.hash.substring(0, 2) == "#!") {
if(window.location.hash.substring(2).length > 2) {
window.location = window.location.hash.substring(2);
} else {
return false;
}
}
return false;
}
window.redirect();
</script>
<script type="text/javascript">
$(function() {
$(window).hashchange(function() {
if(ajax_loading == true) {
return false;
} else {
loadPage(window.location.hash.substring(2), 'internal', '');
}
});
});
</script>
There are two steps to this. The first one checks if there is a hashbang when coming directly to a page by refreshing, or entering the URL for example. If there is a hashbang, redirect to the page stored in the hash.
The second step checks for a change to the hash, which catches the likes of the user pressing the back button, for example.
My issue is with the first block - when a user refreshes or directly enters a URL with a hashbang.
If the user enters http://www.domain.com/pageA#/pageB, any server side code on pageA will run before the window is then redirected pageB
This is causing problems in cases such as:
- User directly goes to pageA - pageA sets a session variable to 'abc'
- User clicks on link to pageB - pageB then sets that session variable to 'xyz' - the URL is currently http://www.domain.com/pageA#/pageB
- User clicks on link to pageC - the session variable is still set to 'xyz' and pageC doesn't change this - the URL is currently http://www.domain.com/pageA#/pageC
- User now hits refresh. pageA is executed first, before redirecting to pageC - but because pageA was executed first, the session variable has now been set back to 'abc' when it should be 'xyz'.
Due to loading the views at the last point of the code within a CodeIgniter controller - I can't do the window redirect at any point other than when the code of the page before the hashbang has executed.
Does any have any ideas of how I can prevent this from happening?