programming, software, technology, anything on my mind...

Long Time No Blog, OH, and Local Storage...


Long time no post! I've been insanely busy with a new house as well as more development responsibilities at my place of occupation. I simply haven't had any time for this blog lately. Anyways I wanted to write up a quick post about a situation I recently encountered, one of those "Why haven't I been doing this all along?" type of moments.

In my projects I use AJAX for searching/displaying records from a database pretty religiously. This is great, put in what you want to search, use a nice spinner while the request is sent, the results populate the page, click 'edit' to edit or view individual records (the usual CRUD screen I guess I should say?). However if you click on one of the records to either edit or view, click the back button, the search results are not present causing the user to 're-search'.

Local Storage

Here comes Local Storage to the rescue! Local Storage is great for key => value storage in a user's browser! I initially found this Stackoverflow post and where a majority of the code below is lifted from. Basically when a search is performed, the contents of the search (the ajax call) are displayed in a DIV box with an ID, say ID equals 'results'. From there the HTML contents are saved ( where ID='results' ) into Local Storage so that when the back button is pressed, the results are pulled from Local Storage and displayed, hence our search results won't be lost.

Example Code

<!-- search box -->
<input type="text" id="search" /> 

<!-- submit button -->
<button id="submit">Search</button>

<!-- results render here -->
<div id="results"></div>

Here's some example code for the 'Search' button, notice I'm adding the hash to the URL on click. That way when a user clicks the back button the Local Storage gets looked up. You could also link back to the hashed URL.

//Example ajax post, or use .get()
    //add a hash to url
    window.location.hash = 'last_search';
    var search = $('#search').val();
    //post or get?
    $.post("https://some/url", { param: search })
        .done( function(data) {
            var $container = $("#results");
        .fail( function(xhr, textStatus, errorThrown) {
            //throw some error message

Inside $(document).ready() when the document loads, check to see if there's a key called 'results' and a hash exists in the URL. This is key for the Local Storage lookup to occur. For example if our URL looks something like this: https://some/url/#last_search , this indicates to pull from Local Storage and display, otherwise https://some/url won't initiate the Local Storage lookup.

    // Replace the search result on document load.
    if (('localStorage' in window) && window['localStorage'] !== null) {
        console.log("document loaded.");

        //if results key in local storage & hash in url
        if ('results' in localStorage && window.location.hash) {
            console.log("getting items in local storage..");

Also, when the document is unloaded save the results HTML into Local Storage!

//Save the search result when leaving the page.
$(window).unload(function () {
    console.log("page unloaded");
    if (('localStorage' in window) && window['localStorage'] !== null) {
        //results div box
        var resultBox = $("#results").html();
        //set results html into localStorage
        localStorage.setItem('results', resultBox);

I recommend reading up on Local Storage as there are many more uses. Thanks for reading!