Overcoming the Cookie Size Limit When Using jQuery DataTables and Saved State

JavaScript , jQuery Add comments

One of the features of the jQuery DataTables plugin is that you can use the configuration option "bStateSave" to store the current view of the table (the sort order, the number of rows displayed, the filter term, etc.) in a cookie, so if the user navigates away from the page then comes back, the table view is the same as how they left it.

However, if your website or web application stores the state of several DataTables, and a user hits all those tables faster than those cookies can expire (their default lifespan is 2 hours but can be customized with the "iCookieDuration" option), the user could hit the browser cookie size limit and start seeing errors on your site.  I ran into this problem today with an application I've been working on.

Fortunately, starting with version 1.9, DataTables provides functions that let developers intercept the process of saving the table state and reloading that state, and the plugin author provides a documentation page on how to use those functions to store the state data in localStorage, which in most browsers allows you to store a few MBs of data per site (far more than the 4K limit per site for cookies):

http://datatables.net/blog/localStorage_for_state_saving

In my case, I decided that I would store the state data in sessionStorage rather than localStorage, but the principle was the same.

2 responses to “Overcoming the Cookie Size Limit When Using jQuery DataTables and Saved State”

  1. Reyur Says:
    Hello.

    Thank you! I had the same problem, and I used the localStorage. But I wanted the cookie is deleted when the browser is closed. With sessionStorage, it's perfect!
    I use jQuery / datatable in Tapestry, so the options are:

    public JSONObject getOptions() {
    String option = "{bJQueryUI : true, bStateSave : true}";
    JSONObject json = new JSONObject(option);

    json.put("fnStateSave", new JSONLiteral("function (oSettings, oData) {sessionStorage.setItem('dt-' + window.location.pathname, JSON.stringify(oData));}"));
    json.put("fnStateLoad", new JSONLiteral("function (oSettings) {return JSON.parse(sessionStorage.getItem('dt-' + window.location.pathname));}"));

    return json;
    }

    Reyur.

    PS : sorry for my bad english !
  2. CharlesDrunk Says:
    cool web site <a href=http://freemilf.net/>http://freemilf.net/</a>;

Leave a Reply