Remember ajax added data when hitting back button
Asked Answered
C

3

46

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 Metallica but add it to the same result list as the previous search.

My problem is when a user clicks on a link to a record, then hits the back button, back to the search result.
FireFox (7) keeps the page as it looked when I left it, displaying the full result.
IE (7,8) and Chrome (15) on the other hand will display the page as it were before adding any search results with AJAX, as if it doesn't remember that I added data to it.

Below is the code I use. I tried to add the location.hash = "test"; but it didn't seem to work.

// Add search result
$("#searchForm").submit(function (event) {
    //location.hash = "test";
    event.preventDefault();

    $.post($(this).attr('action'), $(this).serialize(),
    function (data) {
        $("tbody").append(data);
    });
});  

I don't need a back button that keeps track of changes on the search page, like stepping through each different search result as it was added. I just want the browser to remember the last search result when I hit the back button.

SOLVED
Changing to document.location.hash = "latest search" didn't change anything. I had to use the localStorage as Amir pointed out.

This goes into the rest of the jQuery code:

// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
    if ('myTable' in localStorage && window.location.hash) {
        $("#myTable").html(localStorage.getItem('myTable'));
    }
}

// Save the search result table when leaving the page.
$(window).unload(function () {
    if (('localStorage' in window) && window['localStorage'] !== null) {
        var form = $("#myTable").html();
        localStorage.setItem('myTable', form);
    }
});
Cannabin answered 31/10, 2011 at 16:26 Comment(1)
The lazy guy's workaround would be to use target="_blank" on all your links. This way the back button would not be a problem.Directly
H
17

You have a few options.

  1. Use localstorage to remember the last query
  2. Use cookies (but don't)
  3. Use the hash as you tried with 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.

Heikeheil answered 31/10, 2011 at 16:32 Comment(1)
localstorage will eventually get full.Lockard
C
12

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 );
});
Centroid answered 6/6, 2014 at 13:22 Comment(1)
I like this solution as long as the limitations are acceptable to the project. If you have a search and the results are loaded with ajax and contain a link to a details page for instance, click details page link, then back and results are still there. But if you were to click details page for another item on those results then back again the cache is gone. Great solutionfor certain circumstances tho!Better
T
0

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."

Tynan answered 31/10, 2011 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.