I have a search page where every search result is added to the page with AJAX. This way I can let users search for e.g Led Zeppelin, then do another search for
You have a few options.
document.location.hash = "last search"
to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request. I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible.
I am curious to know why it didn't work. Update your answer so we can help.
I believe you can use the hash section (after the # sign) to differentiate the page pre-ajax call and post-ajax call, that way the back button will take you to the post-ajax call version instead. Can you elaborate on why this solution did not work for you?
This page may help:
http://ajaxpatterns.org/Unique_URLs#Bookmarkable.2C_Linkable.2C_and_Type-In-Able
"Bookmarkable, Linkable, and Type-In-Able
window.location.hash makes the URL unique, so a user can bookmark it, link to it, and type it directly into their browser. window.onload ensures the bookmark is used to set state. Polling or IFrame ensure this will work even when the base URL (before the hash) is the same."
Another solution is to use the facts that INPUT fields are preserved while using back button. So, I do like that :
My page contains an input hidden like that :
<input type="hidden" id="bfCache" value="">
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});